您的位置:首页 > 编程语言 > Python开发

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

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

#使用给定的宽度打印格式化后的价格列表
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方法访问“数据库”实体。

#使用get()的简单数据库
#这里添加代码清单4-1中插入数据库的代码
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)?')

#使用正确的键:
key=request #如果请求既不是'p'也不是'a'
if request =='p': key='phone'
if request =='a': key='addr'

#使用get()提供默认值:
person= people.get(name, {})
label=labels.get(key, key)
result=person.get(key,'not available')

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: