python的字符串格式化序列示例和字典示例

字符串格式化序列的代码将使用星号字段宽度说明符来格式化一张包含水果价格的表格,表格的总宽度由用户输入。因为是由用户提供信息,所以就不能在转换说明符中将字段宽度硬编码。使用星号运算符就可以从转换元组中读出字段宽度。

#使用给定的宽度打印格式化后的价格列表
width=input('Please enter width:')

price_width=10
item_width=width-price_width

header_format='%-*s%*s'
format       ='%-*s%*.2f'

print '='*width

print header_format % (item_width,'Item',price_width,'Price')

print '_'*width

print format %(item_width,'Apples',price_width,0.4)
print format %(item_width,'Pears',price_width,0.5)
print format %(item_width,'Cantaloupes',price_width,1.92)
print format %(item_width,'Dried Apricots(16 oz.)',price_width,8)
print format %(item_width,'Prunes (4 lbs.)',price_width,12)

print '='*width

下面是程序运行示例:

Please enter width:35
===================================
Item Price
___________________________________
Apples 0.40
Pears 0.50
Cantaloupes 1.92
Dried Apricots(16 oz.) 8.00
Prunes (4 lbs.) 12.00
===================================

字典示例

#简单数据库
#使用人名作为键的字典。每个人用另一个字典来表示,其键'phone'和'addr'分别表示他们的电话号码和地址
people={
    'Alice':{
        'phone':'2341',
        'addr':'Foo drive 23'
    },
    
    'Beth':{
       'phone':'9102',
       'addr':'Bar street 42'
    },
    'Cecil':{
        'phone':'3158',
        'addr':'Baz avenue 90'
    }
}

#针对电话号码和地址使用的描述性标签,会在打印输出的时候用到
labels={
    'phone': 'phone number',
    'addr': 'address'
}

name = raw_input('Name:')

#查找电话号码还是地址?使用正确的键:
request = raw_input('Phone number (p) or address (a)?')

#使用正确的键:
if request =='p': key='phone'
if request =='a': key='addr'

#如果名字是字典中的有效键才打印信息:
if name in people: print "%s's %s is %s."%\
     (name, labels[key], people[name][key])

下面是程序运行的示例:

Name:Beth
Phone number (p) or address (a)?p
Beth's phone number is 9102.

下面是代码清单演示了上面程序的修订版本,它使用get方法访问“数据库”实体。

 1 #使用get()的简单数据库
 2 #这里添加代码清单4-1中插入数据库的代码
 3 people={
 4     'Alice':{
 5         'phone':'2341',
 6         'addr':'Foo drive 23'
 7     },
 8     
 9     'Beth':{
10        'phone':'9102',
11        'addr':'Bar street 42'
12     },
13     'Cecil':{
14         'phone':'3158',
15         'addr':'Baz avenue 90'
16     }
17 }
18 labels={
19     'phone':'phone number',
20     'addr':'address'
21     }
22 
23 name=raw_input('Name:')
24 
25 #查找电话号码还是地址?
26 request=raw_input('Phone number (p) or address (a)?')
27 
28 #使用正确的键:
29 key=request #如果请求既不是'p'也不是'a'
30 if request =='p': key='phone'
31 if request =='a': key='addr'
32 
33 #使用get()提供默认值:
34 person= people.get(name, {})
35 label=labels.get(key, key)
36 result=person.get(key,'not available')
37 
38 print "%s's %s is %s." % (name, label, result)

下面是程序执行的例子。注意get方法带来的灵活性如何使得程序在用户输入我们并未准备的值时也能做出合理的反应。

Name:Cecil
Phone number (p) or address (a)?batting average
Cecil's batting average is not available.

 

 


 

posted @ 2017-10-19 12:39  在云中漫步  阅读(1656)  评论(0编辑  收藏  举报