python十二:字符串格式化
生活随笔
收集整理的这篇文章主要介绍了
python十二:字符串格式化
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
# python的字符串格式化有两种: 百分号方式,format方式
s = "Hello %s, Hello %s" % ("world", "python")
print(s)s = "Hello %s, Hello %s, python is %d years" % ("world", "python", 27)
print(s)# 打印浮点数
tp1 = "float %f" % 10.987654621
print(tp1)
# 打印百分比
tp1 = "float %.2f%%" % 10.987654621
print(tp1)# 通过字典
s = "Hello %(name)s, python is %(age)d years" % {"name": "world", "age": 27}
print(s)
tp = "three country, liu{}, guan{}, zhang{}".format("bei","yu","fei")
print(tp)# 通过索引,取值
tp = "three country, liu{2}, guan{0}, zhang{1}".format("bei","yu","fei")
print(tp)# 通过字典方式一
tp = "three country, liu{name1}, guan{name2}, zhang{name3}".format(name1="bei",name2="yu",name3="fei")
print(tp)# 通过字典方式二(传递字典,要加上**)
tp = "three country, liu{name1}, guan{name2}, zhang{name3}".format(**{"name1":"yu","name2":"fei","name3":"bei"})
print(tp)# 通过索引,取值
tp = "three country, liu{1[0]}, guan{1[1]}, zhang{1[2]}".format(["a","b","c"],["ab","cd","ef"])
print(tp)tp = "three country, liu{:s}, {:d}国, {:.2f}年".format("bei", 3, 279.987654)
print(tp)# format()传递列表,要加上*
tp = "three country, guan{:s}, {:d}国, {:.2f}年".format(*["yu", 3, 280.987654])
print(tp)
tp = "three country, guan{name:s}, {country:d}国, {age:.2f}年".format(name="yu",country=3,age=279.7655432)
print(tp)# number b:二进制 o:八进制 d:十进制 x:小写的十六进制 X:大写的十六进制
tp = "number: {:b}, {:o}, {:d}, {:x}, {:X}, {:%}".format(15, 15, 15, 15, 15, 0.15987654321)
print(tp)
总结
以上是生活随笔为你收集整理的python十二:字符串格式化的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: python十一:集合(set)
- 下一篇: python十三:函数