码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-10-19 13:55:55      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:编码   字典   bsp   说明   key   apple   number   ber   add   

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

#使用给定的宽度打印格式化后的价格列表
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.

 


 

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

标签:编码   字典   bsp   说明   key   apple   number   ber   add   

原文地址:http://www.cnblogs.com/zzw818/p/7691870.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!