赞
踩
废话不多说,直接上代码
def str_format():
context1 = '''there is a person, name: %s, age: %d, salary: %d''' %("lucy", 18, 2000)
context2 = '''there is a person, name: %(name)s, age: %(age)d, salary: %(salary)d''' %dict(name="lili",age=19, salary=3000)
context3 = '''there is a person, name: {0}, age: {1}, salary: {2}'''.format("koko", 20, 4000)
# 3.6以后的版本,推荐使用
name, age, salary = "hanmeimei", 16, 6000
context4 = f'''there is a person, name is {name}, age is: {age}, salary is: {salary}'''
print(context1)
print(context2)
print(context3)
print(context4)
代码输出
there is a person, name: lucy, age: 18, salary: 2000
there is a person, name: lili, age: 19, salary: 3000
there is a person, name: koko, age: 20, salary: 4000
there is a person, name is hanmeimei, age is: 16, salary is: 6000
f-string, formatted string literals,是python 3.6以后引入的操作。在此之前,格式化字符串常用的方法为%格式化与str.format()的方法。
而采用f-string方法,好处主要如下:
1.操作更加直观:{}标明直接被替换的变量。
2.操作更加简单:直接在字符串前面加上f即可。
3.性能也要更优于传统的格式化方法。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。