python格式化输出

作者: python 发布时间: 2022-10-16 浏览: 694 次 编辑

python格式化输出

程序中经常会有这样场景:要求用户输入信息,然后打印成固定的格式。占位符:%s(字符串占位符:可以接收字符串,也可接收数字) %d(数字占位符:只能接收数字)

#%s的使用
print('My name is %s,my age is %s' %('aaa',18))
>>>My name is aaa,my age is 18

#%d的使用
print('My name is %s,my age is %d' %('egon',18))
>>>My name is aaa,my age is 18

print('My name is %s,my age is %d' %('egon','18')) 
#报错

以字典形式传值,可以不考虑位置

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

str.format:兼容性好

#按照位置传值
res = "my name is {}, my age is {}".format('aaa',18)
print(res)

#不按照位置
res = "my name is {name}, my age is {age}".format("age":18,"name":"aaa")
print(res)