格式化輸出的幾種方式

weixin_49658844發表於2020-12-20

格式化輸出的幾種方式

第一種:str.format----------常用方式----python版本2.6

對順序有要求

res = "my name is {} , my age is {}".format("sun",18)
print(res)

對順序無要求

res = "my name is {name} , my age is {age}".format(name = "sun", age = 18)
print(res)

按照索引

res = "my name is {0} , my age is {1}".format( "sun",18)

第二種:%s

對順序有要求

res = "my name is %s,my age is %s" % ("sun", 20)
print(res)

對順序無要求

res = "my name is %(name)s,my age is %(age)s" % {"age": 18, "name": "sun"}
print(res)

name = 'sun'
age = 18
res = "my name is %(name)s,my age is %(age)s" % (name,age)
print(res)

第三種:f ----python3.5版本以後

對順序無要求

x = "sun" 
y = 18
res = f'my name is {x} , my age is {y}'
print(res)

相關文章