字符串是Pyhon中的常用的数据类型,这篇文章主要为大家详细介绍一下python字符串的格式化教程。
在Python 3.6之前,有两种将Python表达式嵌入到字符串文本中进行格式化的主要方法:%-formatting和str.format()
一、%-formatting
1
2
3
name = "Eric"
age = 74
"Hello, %s. You are %s." % (name, age)
注:这种格式不是很好,因为它是冗长的,会导致错误。
二、str.format()
str.format() 在Python 2.6中引入的。
(1)使用str.format(),替换字段用大括号标记:
1
"Hello, {}. You are {}.".format(name, age)
# 输出结果:'Hello, Eric. You are 74.'
(2)可以通过引用其索引来以任何顺序引用变量:
1
"Hello, {1}. You are {0}-{0}.".format(age, name)
# 输出结果:'Hello, Eric. You are 74-74.'
(3)如果插入变量名称,则会获得额外的能够传递对象的权限,然后在大括号之间引用参数和方法:
1
2
person = {'name': 'Eric', 'age': 74}
"Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
# 输出结果:'Hello, Eric. You are 74.'
(4)可以使用**来用字典来完成这个巧妙的技巧:
1
2
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
1
2
3
name = "Eric"
age = 74
f"Hello, {name}. You are {age}."
# 输出结果:'Hello, Eric. You are 74.'
(2)用大写字母F也是有效的:
1
2
3
name = "Eric"
age = 74
F"Hello, {name}. You are {age}."
# 输出结果:'Hello, Eric. You are 74.'
(3)可以调用函数
1
2
3
name = "Eric"
age = 74
f"{name.lower()} is funny."
# 输出结果:'eric is funny.'
1
f"{2 * 37}"
# 输出结果:'74'
(4)可以使用带有f字符串的类创建对象
1
2
3
4
5
6
7
8
9
10
11
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.'
1
f"{new_comedian!r}"
# 输出结果:'Eric Idle is 74. Surprise!'
(5)多行f-string
1
2
3
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.'
1
2
3
message = (f"Hi {name}. "
"You are a {profession}. "
"You were in {affiliation}.")
# 输出结果:'Hi Eric. You are a {profession}. You were in {affiliation}.'
(6)使用"“”
1
2
3
4
5
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-字符串是运行时渲染的表达式,而不是常量值。
————————————————
版权声明:本文为CSDN博主「hdxx2022」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/hdxx2022/article/details/128383263