什么是格式化输出?
我们写程序时,可能会用到一段字符串多次,比如:我的名字是xxx,年龄xxx,
每次写的时候’我的名字’和’年龄’需要重复写。我们可以写一个特定的字符串,使用时只需填入姓名和年龄即可。
通俗来说就是:改变固定字符串的某些字符。
下面介绍三种方法:
1.占位符
ps:占位符分好多种,我们只需记%s足够使用
1.根据位置
words = "my name is %s,age is %s" %("alex",18)
print(words) 结果为:my name is alex,age is 18
2.根据关键字
words = "my name is %(name)s,age is %(age)s" %{"name":"alex","age":18}
print(words) 结果为:my name is alex,age is 18
2.string.format()
1.根据位置
words = "my name is {},age is {}".format("alex",123)
print(words) 结果为:my name is alex,age is 123
2.根据索引
words = "my name is {0},age is {1},name is {1},age is {0}".format("alex",123)
print(words) 结果为:my name is alex,age is 123,name is 123,age is alex
3.根据关键字
words = "my name is {name},age is {age}".format(name="alex",age=123)
print(words) 结果为:my name is alex,age is 123
3.f-string
1.输入内容可以是字符串
name = "alex"
age = 456
words = f'name is {name},age is {age}'
print(words) 结果为:name is alex,age is 456
2.输入的内容也可以是表达式
def func():
return "hhhh"
words = f'{func()}'
print(words) 结果为:hhhh
三种方式的比较:
- 占位符是最早推出的,但速度比较慢
- f-string是python3.5以后才有的,速度比较快
- format的话则是中规中矩,我个人喜欢用format