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)
- 下一篇: c一:指针引用(int * p )和指针