在Python中,有几种不同的字符串格式化方法。以下是所有的格式化字符串字面值以及其他常用的字符串格式化方法:
1. f-string(格式化字符串字面值)
从Python 3.6开始引入,使用f
或F
前缀,可以在字符串中嵌入表达式和变量:
name = "Alice"
age = 30
formatted_string = f"Hello, {name}. You are {age} years old."
print(formatted_string)
# 输出: Hello, Alice. You are 30 years old.
2. 原始字符串(Raw String)
使用r
或R
前缀,创建原始字符串,反斜杠``不会被解释为转义字符:
raw_string = r"C:\Users\name\path"
print(raw_string)
# 输出: C:\Users\name\path
3. 字节字符串(Byte String)
使用b
或B
前缀,创建字节字符串,用于处理二进制数据:
byte_string = b"Hello, World!"
print(byte_string)
# 输出: b'Hello, World!'
4. Unicode 字符串
在Python 3中,所有字符串默认是Unicode字符串。在Python 2中,使用u
或U
前缀表示Unicode字符串:
# 适用于 Python 2
unicode_string = u"Hello, Unicode!"
print(unicode_string)
# 输出: Hello, Unicode!
5. 多行字符串
使用三引号"""
或'''
创建多行字符串:
multiline_string = """This is a
multiline string."""
print(multiline_string)
# 输出:
# This is a
# multiline string.
其他字符串格式化方法
6. 百分号格式化(% Formatting)
这是Python旧版的字符串格式化方式:
name = "Alice"
age = 30
formatted_string = "Hello, %s. You are %d years old." % (name, age)
print(formatted_string)
# 输出: Hello, Alice. You are 30 years old.
7. str.format() 方法
这是Python 3引入的一种格式化字符串的方法:
name = "Alice"
age = 30
formatted_string = "Hello, {}. You are {} years old.".format(name, age)
print(formatted_string)
# 输出: Hello, Alice. You are 30 years old.
8. Template Strings
使用string
模块中的Template
类进行简单的字符串替换:
from string import Template
name = "Alice"
age = 30
template = Template("Hello, $name. You are $age years old.")
formatted_string = template.substitute(name=name, age=age)
print(formatted_string)
# 输出: Hello, Alice. You are 30 years old.
示例代码
综合上述所有格式化字符串方法的示例代码:
name = "Alice"
age = 30
# f-string
f_string = f"Hello, {name}. You are {age} years old."
# 原始字符串
raw_string = r"C:\Users\name\path"
# 字节字符串
byte_string = b"Hello, World!"
# 多行字符串
multiline_string = """This is a
multiline string."""
# 百分号格式化
percent_format = "Hello, %s. You are %d years old." % (name, age)
# str.format() 方法
str_format = "Hello, {}. You are {} years old.".format(name, age)
# Template Strings
from string import Template
template = Template("Hello, $name. You are $age years old.")
template_string = template.substitute(name=name, age=age)
print(f_string)
print(raw_string)
print(byte_string)
print(multiline_string)
print(percent_format)
print(str_format)
print(template_string)
这些方法涵盖了Python中所有的格式化字符串字面值和其他常用的字符串格式化方法。选择适合你需求的方法可以使你的代码更加简洁和易读。
作者:血舞之境
链接:https://juejin.cn/post/7368421971383992332
来源:稀土掘金