一堆堆的烂数据里面有很多的字符串,老是会用到格式化字符串。一般Python 格式化字符串方法有 "%"操作符、format两种,今天要推荐的是第三种方法——formatted string literals。
①第一种是上古时代的方法,Python2.6 以前独霸天下的 " % "操作符:
name = 'a'
age = 'b'
sex = 'c'
like = 'd'
country = 'e'
print('Hello, my name is %s, %s years old, from %s, sex is %s, like %s.'%(name, age, country, sex, like))
运行结果:Hello, my name is a, b years old, from e, sex is c, like d.
这种方法当变量多的时候,使用起来会很麻烦。
②第二种是 'format '。Python2.6 引入,性能比 % 更强大。大概有三种写法:
- a) 替换字段直接用大括号
name = 'a'
age = 'b'
sex = 'c'
like = 'd'
country = 'e'
print('Hello, my name is {}, {} years old, from {}, sex is {}, like {}.'.format(name, age, country, sex, like))
运行结果:Hello, my name is a, b years old, from e, sex is c, like d.
- b) 通过大括号 + 索引引用变量
name = 'a'
age = 'b'
sex = 'c'
like = 'd'
country = 'e'
print('Hello, my name is {1}, {0} years old, from {3}, sex is {2}, like {4}.'.format(age, name, sex, country, like))
运行结果:Hello, my name is a, b years old, from e, sex is c, like d.
代码中{1}索引的是name,{0}索引的是age,{2}索引的是sex,{3}索引的是country,{4}索引的是like。
- c) 使用键值对的方式
name = 'a'
age = 'b'
sex = 'c'
like = 'd'
country = 'e'
print('Hello, my name is {name}, {age} years old, from {country}, sex is {sex}, like {like}.'.format(age = age, name = name, sex = sex, country = country, like = like))
运行结果:Hello, my name is a, b years old, from e, sex is c, like d.
这种方法format的大括号和变量名是分开的,当变量多的时候,使用起来会很容易把人搞晕。
③第三种是formatted string literals。它是在 Python3.6 新加的字符串格式化方法,这种方法是在字符串前面加上 “f”,大括号直接使用变量,所以又叫 ‘f-strings’。
name = 'a'
age = 'b'
sex = 'c'
like = 'd'
country = 'e'
print(f'Hello, my name is {name}, {age} years old, from {country}, sex is {sex}, like {like}.')
运行结果:Hello, my name is a, b years old, from e, sex is c, like d.
它还可以进行内联运算,也就是大括号里面还可以写算术表达式:
>>> f’{1 + 2 + 3}’
‘6’
它还可以直接调用函数:
>>>name = ‘A’
>>> f’ {name.lower()}’
’ a’
相比于 ‘%’ 和 ‘format’,f-string 的性能更好,运行速度更快,如果你的 Python 是 3.6 及以上的,非常建议用 f-string!
更多用法详见Formatted string literals的官方文档。