在 Python 3.6 之前,字符串格式化方法主要有两种:%格式化 和 str.format()。下面我们简单看下它们的使用方法,以及局限。
1 %-格式化
% 格式化方法从 Python 刚开始时就存在了,堪称「一届元老」,但是 Python 官方文档中并不推荐这种格式化方式:
这里描述的格式化操作容易表现出各种问题,导致许多常见错误(例如无法正确显示元组和字典)。
使用较新的格式化字符串文字或 str.format() 可以有助于避免这些错误。这些替代方案还提供了更强大,灵活和可扩展的格式化文本方法。
1.1 如何使用 %格式化
一般使用方式,要插入多个变量的话,必须使用元组:
name = “hoxis”
age = 18
“hello, %s. you are %s ?” %(name, age)
‘hello, hoxis. you are 18 ?’
1.2 %格式化的缺陷
上面的代码示例看起来还能读,但是,一旦开始使用多个参数和更长的字符串,你的代码将很快变得不那么容易阅读:
name = “hoxis”
age = 18
country = “China”
hair = “black”
“hello, %s. you are %s ?. Your country is %s, and your hair is %s” %(name, age, country,hair)
‘hello, hoxis. you are 18 ?. Your country is China, and your hair is black’
可以看出,这种格式化并不是很好,因为它很冗长并且容易导致错误,比如没有正确显示元组或字典。
不过还好我们还有 str.format()。
2 str.format()
Python 2.6 中引入了 str.format() 格式化方法:https://docs.python.org/3/library/stdtypes.html#str.format。
2.1 str.format() 的使用
str.format() 是对 %格式化 的改进,它使用普通函数调用语法,并且可以通过 format() 方法为对象进行扩展。
使用 str.format() 时,替换字段用大括号进行标记:
“hello, {}. you are {}?”.format(name,age)
‘hello, hoxis. you are 18?’
并且可以通过索引来以其他顺序引用变量:
“hello, {1}. you are {0}?”.format(age,name)
‘hello, hoxis. you are 18?’
或者可以这样:
“hello, {name}. you are {age1}?”.format(age1=age,name=name)
‘hello, hoxis. you are 18?’
从字典中读取数据时还可以使用 **:
person = {“name”:“hoxis”,“age”:18}
“hello, {name}. you are {age}?”.format(**person)
‘hello, hoxis. you are 18?’
确实,str.format() 比 %格式化高级了一些,但是它还是有自己的缺陷。
2.2 str.format() 的缺陷
在处理多个参数和更长的字符串时仍然可能非常冗长,麻烦!看看这个:
“hello, {}. you are {} ?. Your country is {}, and your hair is {}”.format(name, age, country,hair)
‘hello, hoxis. you are 18 ?. Your country is China, and your hair is black’
3 f-Strings
还好,现在我们有了 f-Strings,它可以使得字符串格式化更加容易。
f-strings 是指以 f 或 F 开头的字符串,其中以 {} 包含的表达式会进行值替换。
下面从多个方面看下 f-strings 的使用方法,看完后,我相信你会对「人生苦短,我用 Python」有更深地赞同~
3.1 f-Strings 使用方法
name = ‘hoxis’
age = 18
f"hi, {name}, are you {age}"
‘hi, hoxis, are you 18’F"hi, {name}, are you {age}"
‘hi, hoxis, are you 18’
是不是很简洁?!还有更牛叉的!
因为 f-strings 是在运行时计算的,那么这就意味着你可以在其中放置任意合法的 Python 表达式,比如:
运算表达式
f"{ 2 * 3 + 1}"
‘7’
调用函数
还可以调用函数:
def test(input):
… return input.lower()
…name = “Hoxis”
f"{test(name)} is handsome."
‘hoxis is handsome.’
也可以直接调用内置函数:
f"{name.lower()} is handsome."
‘hoxis is handsome.’
在类中使用class Person:
… def init(self,name,age):
… self.name = name
… self.age = age
… def str(self):
… return f"{self.name} is {self.age}"
… def repr(self):
… return f"{self.name} is {self.age}. HAHA!"
…hoxis = Person(“hoxis”,18)
f"{hoxis}"
‘hoxis is 18’f"{hoxis!r}"
‘hoxis is 18. HAHA!’print(hoxis)
hoxis is 18hoxis
hoxis is 18. HAHA!
多行 f-stringname = ‘hoxis’
age = 18
status = ‘Python’
message = {
… f’hi {name}.’
… f’you are {age}.’
… f’you are learning {status}.’
… }message
{‘hi hoxis.you are 18.you are learning Python.’}
这里需要注意,每行都要加上 f 前缀,否则格式化会不起作用:
message = {
… f’hi {name}.’
… ‘you are learning {status}.’
… }message
{‘hi hoxis.you are learning {status}.’}
参考博文:点这里