字符串格式化

"""
字符串格式化
"""
msg = "i am" + " cql " + " abc" # 效率低,开辟内存空间大
print(msg)

# %s 可以接收一切
print("i am %s, %s" % ("aaa", [1 ,2]))
print("i am %s, %s" % ("aaa", 11))
print("i am %s, %s" % ("aaa", "aa"))
print("i am %s, %s" % ("aaa", (1, 2)))
# %d只能接收int类型
print("i am %s, %d" % ("aaa", 12))
# %f
print("i am %s, %f" % ("aaa", 12.0)) # i am aaa, 12.000000 默认显示6位小数
print("i am %s, %.2f" % ("aaa", 12.0)) # i am aaa, 12.00 只显示2位小数%.2f
print("i am %s, %.2f%%" % ("aaa", 12.0)) # i am aaa, 12.00%, %% 打印%
# format 字典形式
print("i am %(name)s age %(age)d" % {"name":"cql", "age":12}) # i am cql age 12
print("i am %(pp).2f" % {"pp": 19.889}) # i am 19.89

# 宽度
print("i am %+20s" % "cql") # i am cql

# 按指定字符分隔组合显示
print("root", "***", 0, 0, sep=":") # root:***:0:0



format

tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')

tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])

tpl = "i am {0}, age {1}, really {0}".format("seven", 18)

tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])

tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)

tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})

tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])

tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)

tpl = "i am {:s}, age {:d}".format(*["seven", 18])

tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)

tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})

tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
print(tpl)
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)

tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)

tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)


原文地址:https://www.cnblogs.com/Windows-phone/p/9720606.html