1. 使用 fstring(格式化字符串字面量)Python 3.6 引入了一种新的字符串格式化方法,称为 fstring,它提供了一种快速、简洁的方式来嵌入表达式到字符串中。fstring 使用大括...
Python 3.6 引入了一种新的字符串格式化方法,称为 f-string,它提供了一种快速、简洁的方式来嵌入表达式到字符串中。f-string 使用大括号 {} 来包含变量,这些变量会被替换为它们的值。
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old."): 和空格。% 格式化这是 Python 中最传统的字符串格式化方法,使用 % 符号来插入变量。
name = "Bob"
age = 25
print("My name is %s and I am %d years old." % (name, age))str.format() 方法是 Python 2.6 及以上版本提供的一种格式化字符串的方法,它提供了一种灵活的方式来插入变量。
name = "Charlie"
age = 35
print("My name is {} and I am {} years old.".format(name, age))模板字符串是使用 Python 的 string 模块中的 Template 类来实现的。这种方法适用于需要动态替换字符串中的多个部分的情况。
from string import Template
template = Template("My name is $name and I am $age years old.")
name = "David"
age = 40
print(template.substitute(name=name, age=age))format_map() 方法format_map() 方法是 str.format() 方法的一个扩展,它允许你使用字典来格式化字符串。
info = {'name': 'Eve', 'age': 45}
print("My name is {name} and I am {age} years old.".format(**info))str.format() 方法。通过以上五种技巧,你可以根据不同的需求选择最合适的字符串格式化方法,从而提升代码的可读性和效率。在实际开发中,选择合适的格式化方法可以让你编写出更加清晰、高效的代码。