资源描述:
《python字符串格式化示例.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、1、字符串格式化如何输出格式化的字符串。我们经常会输出类似'亲爱的xxx你好!你xx月的话费是xx,余额是xx'之类的字符串,而xxx的内容都是根据变量变化的,所以,需要一种简便的格式化字符串的方式。示例:>>>print("Hi%s,yourscoreis%d."%('jack',69))Hijack,yourscoreis69.>>>print("亲爱的%s你好!你的%d月的话费是%d,余额是%d"%('jack',7,169,45.5))亲爱的jack你好!你的7月的话费是169,余额是45s = "my name is %
2、s,age is %d" %('chentujin',29)print(s)s1 = "my name is %(name)s,age is %(age)d" %{'name':'chentujin','age':999}print(s1)s2 = "percent %.2f" % 99.12311print(s2)s3 = "i am %(pp).2f" %{'pp':99., }print(s3)#s4 = "i am %.3f %%" %{"aa": 88., }#print(s4)%运算符就是用来格式化字符串的。在字符串内
3、部,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。常见的占位符有:%d整数%f浮点数%s字符串2、format格式化示例2:s5 = "my name is {0},today is {1},cname is {0}".format('chentujin',29)print(s5)s6 = "***********{name:s}-------------{age:d}".format(name='jack',age=29)print(s6)s7
4、= "----------{:9^20s}-----------".format('陈土金') #^代表居中对齐,20代表占位符,占20个字符位置,9不够20字符用9填充print(s7)s8 = "my name is {name:s},age is{age:d}" .format(name='chentujin',age=29)print(s8)s9 = "my name is %s,age is %d" %('jack',29)print(s9)s10 = "chentujin is {name:s},age is{age
5、:d}" .format(name='mike',age=20)print(s10)s11 = "my name is {0},cname is{1}" .format('jack',29)print(s11)tpl="iam{},age{},{}".format("jack",29,'shanghai')print(tpl)tpl="iam{},age{},{}".format(*["mike",29,'shanghai'])print(tpl)tpl="iam{name},age{age},{from}".format(**{
6、"name":"mike",'age':29,"from":'shanghai'})print(tpl)输出结果:iamjack,age29,shanghaiiammike,age29,shanghaiiammike,age29,shanghai