Python字符串格式化实例讲解

发布时间:

在Python 3.6之前,有两种将Python表达式嵌入到字符串文本中进行格式化的主要方法:%-formatting和str.format()

Python字符串格式化实例讲解

一、%-formatting

name = "Eric"
age = 74
"Hello, %s. You are %s." % (name, age)

注:这种格式不是很好,因为它是冗长的,会导致错误。

二、str.format()

str.format() 在Python 2.6中引入的。

(1)使用str.format(),替换字段用大括号标记:

"Hello, {}. You are {}.".format(name, age)

# 输出结果:'Hello, Eric. You are 74.'

(2)可以通过引用其索引来以任何顺序引用变量:

"Hello, {1}. You are {0}-{0}.".format(age, name)

# 输出结果:'Hello, Eric. You are 74-74.'

(3)如果插入变量名称,则会获得额外的能够传递对象的权限,然后在大括号之间引用参数和方法:

person = {'name': 'Eric', 'age': 74}
"Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])

# 输出结果:'Hello, Eric. You are 74.'

(4)可以使用**来用字典来完成这个巧妙的技巧:

person = {'name': 'Eric', 'age': 74}
"Hello, {name}. You are {age}.".format(**person)

# 输出结果:'Hello, Eric. You are 74.'

注:当处理多个参数和更长的字符串时,str.format()仍然可能非常冗长。

三、f-Strings

f-Strings是在Python 3.6开始加入标准库。也称为“格式化字符串文字”F字符串是开头有一个f的字符串文字,以及包含表达式的大括号将被其值替换。

(1)f-Strings

name = "Eric"
age = 74
f"Hello, {name}. You are {age}."

# 输出结果:'Hello, Eric. You are 74.'

(2)用大写字母F也是有效的:

name = "Eric"
age = 74
F"Hello, {name}. You are {age}."

# 输出结果:'Hello, Eric. You are 74.'

(3)可以调用函数

name = "Eric"
age = 74
f"{name.lower()} is funny."

# 输出结果:'eric is funny.'

f"{2 * 37}"

# 输出结果:'74'

(4)可以使用带有f字符串的类创建对象

class Comedian:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def __str__(self):
return f"{self.first_name} {self.last_name} is {self.age}."
def __repr__(self):
return f"{self.first_name} {self.last_name} is {self.age}. Surprise!"
new_comedian = Comedian("Eric", "Idle", "74")
f"{new_comedian}"

# 输出结果;'Eric Idle is 74.'

f"{new_comedian!r}"

# 输出结果:'Eric Idle is 74. Surprise!'

(5)多行f-string

message = (f"Hi {name}. "
f"You are a {profession}. "
f"You were in {affiliation}.")

# 输出结果:'Hi Eric. You are a comedian. You were in Monty Python.'

message = (f"Hi {name}. "
"You are a {profession}. "
"You were in {affiliation}.")

# 输出结果:'Hi Eric. You are a {profession}. You were in {affiliation}.'

(6)使用"“”

message = f"""
Hi {name}. 
You are a {profession}. 
You were in {affiliation}.
 """

# 输出结果:'\n Hi Eric. \n You are a comedian. \n You were in Monty Python.\n '

(7)性能

f字符串中的f也可以代表“速度快”。f-字符串是运行时渲染的表达式,而不是常量值。

速度比较:

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
%%timeit
name = "Eric" 
age = 74 
'%s is %s.' % (name, age)
# 202 ns ± 2.05 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%%timeit
name = "Eric" 
age = 74 
'{} is {}.'.format(name, age)
# 244 ns ± 5.52 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%%timeit
name = "Eric" 
age = 74 
'{name} is {age}.'
# 14.4 ns ± 0.0121 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

(8)语法正确格式

f"{'Eric Idle'}"

# 输出结果:'Eric Idle'

f'{"Eric Idle"}'

# 输出结果:'Eric Idle'

f"""Eric Idle"""

# 输出结果:'Eric Idle'

f'''Eric Idle'''

# 输出结果:'Eric Idle'

f"The \"comedian<span class="string">" is {name}, aged {age}."

# 输出结果:'The "comedian" is Eric, aged 74.'

(9)字典

字典的键使用单引号,请记住确保对包含键的f字符串使用双引号。

comedian = {'name': 'Eric Idle', 'age': 74}
f"The comedian is {comedian['name']}, aged {comedian['age']}."

# 输出结果:'The comedian is Eric Idle, aged 74.'

(10)大括号

为了使字符串出现大括号,您必须使用双大括号:

f"{{74}}"

# 输出结果:'{74}'

f"{{{{74}}}}"

# 输出结果:'{{74}}'