《Python核心编程》第二版第六章练习题答案-第二部分

 

6–6. 字符串.

创建一个string.strip()的替代函数:接受一个字符串,去掉它前面和后面的
空格(如果使用string.*strip()函数那本练习就没有意义了)

解答:

#/usr/bin/python
#!Filename:6-6.py
'''
Created on 2012-7-24

@author: wanglei
'''
def mystrip(astring):
    alist=list(astring)
    list_len=len(alist)
    while alist[0]==" ":
        del alist[0]
    while alist[len(alist)-1]==" ":
        del alist[len(alist)-1]
    print "".join(alist)
bstring=raw_input("please input a string: ")
mystrip(bstring)

测试数据:

please input a string:     python is good   
python is good

注意:输入的字符串前后都有若干空格

6–8. 列表.给出一个整数值,返回代表该值的英文,比如输入89 返回"eight-nine"。附加题:
能够返回符合英文语法规则的形式,比如输入“89”返回“eighty-nine”。本练习中的值限定在0
到1,000.

解答:

#  -*- coding:utf-8 -*- 
#!/usr/bin/python
#Filename:6-8.py
'''
Created on 2012-7-24

@author: wanglei
'''
#原题目,函数返回一个整数的普通英文表示
def returnchar(num):
    dic={'0':'zero','1':'one','2':'two','3':'three','4':'four','5':'five','6':'six',\
         '7':'seven','8':'eight','9':'nine'}
    result=""
    for i in num:
        result +=dic[i]+"-"
    result=result[:-1]
    print result
#附加题,函数返回一个整数的正规英文表示
def returnformalchar(num):
    dic_unit={'0':'zero','1':'one','2':'two','3':'three','4':'four','5':'five','6':'six',\
              '7':'seven','8':'eight','9':'nine','10':'ten'}
    dic_decade={'11':'eleven','12':'twelve','13':'thirteen','14':'fourteen','15':'fifteen',\
                '16':'sixteen','17':'seventeen','18':'eighteen','19':'nineteen','20':'twenty'}
    dic_decade2={'2':'twenty','3':'thirty','4':'forty','5':'fifty','6':'sixty','7':'seventy',\
                 '8':'eighty','9':'ninety'}
    intnum=int(num)
    result=""
    #这个函数专门处理21到99之间的数据
    def returnchar2xto9x(mynum):
        myresult=dic_decade2[mynum[0]]+"-"+dic_unit[mynum[1]]
        return myresult
    if intnum>1000:
        print "输入的数字超出范围了"
        return
    if intnum<11:
        result=dic_unit[num]
    elif intnum<21:
        #if num==20:
        #   result="twenty"
        #else:
            result=dic_decade[num]
    elif intnum<100:
        result=returnchar2xto9x(num)
    else:
        result=dic_unit[num[0]]+" hundred-"+returnchar2xto9x(num[1:])
    print result
num=raw_input("input a num: ")
returnformalchar(num)

测试数据:

input a num: 321
three hundred-twenty-one

posted on 2012-07-25 11:29  温柔的暴力  阅读(2141)  评论(0编辑  收藏  举报

导航