python字符串的8种格式化方法

在Python中,有几种不同的字符串格式化方法。以下是所有的格式化字符串字面值以及其他常用的字符串格式化方法:

1. f-string(格式化字符串字面值)

从Python 3.6开始引入,使用fF前缀,可以在字符串中嵌入表达式和变量:

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)

使用rR前缀,创建原始字符串,反斜杠``不会被解释为转义字符:

raw_string = r"C:\Users\name\path"
print(raw_string)
# 输出: C:\Users\name\path

3. 字节字符串(Byte String)

使用bB前缀,创建字节字符串,用于处理二进制数据:

byte_string = b"Hello, World!"
print(byte_string)
# 输出: b'Hello, World!'

4. Unicode 字符串

在Python 3中,所有字符串默认是Unicode字符串。在Python 2中,使用uU前缀表示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
来源:稀土掘金

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值