在 Python 中打印原始字符串(带有转义字符)
使用 repr()
函数打印带有转义字符的原始字符串,例如 print(repr(my_str))
。 repr()
函数返回一个字符串,其中包含所提供对象的可打印表示形式。
my_str = 'one\ttwo\nthree'
# ✅ 打印带有转义字符的字符串 (repr())
print(repr(my_str)) # 👉️ 'one\ttwo\nthree'
# ------------------------------------------------
# ✅ 使用转义字符将字符串转换为字节对象
my_bytes = my_str.encode('unicode_escape')
print(my_bytes) # 👉️ b'one\\ttwo\\nthree'
# ------------------------------------------------
# ✅ 打印带有转义字符的字符串(encode() 和 decode())
result = my_str.encode('unicode_escape').decode()
print(result) # 👉️ one\ttwo\nthree
第一个示例使用 repr()
函数打印带有转义序列的原始字符串。
my_str = 'one\ttwo\nthree'
print(repr(my_str)) # 👉️ 'one\ttwo\nthree'
repr()
函数返回所提供对象的可打印表示,而不是字符串本身。
如果我们有权访问变量的声明,则可以在字符串前加上 r
以将其标记为原始字符串。
my_str = r'one\ttwo\nthree'
print(my_str) # 👉️ one\ttwo\nthree
以
r
为前缀的字符串称为原始字符串,并将反斜杠视为文字字符。
如果我们需要在原始字符串中插入变量,请使用格式化字符串文字。
variable = 'two'
my_str = fr'one\t{variable}\nthree'
print(my_str) # 👉️ 'one\ttwo\nthree'
格式化字符串文字
f-strings
让我们通过在字符串前加上 f 来在字符串中包含表达式。
确保将表达式用大括号括起来 - {expression}
。
请注意
,我们在字符串前加上了fr
而不仅仅是f
。
或者,我们可以使用 str.encode()
和 bytes.decode()
方法。
my_str = 'one\ttwo\nthree'
my_bytes = my_str.encode('unicode_escape')
print(my_bytes) # 👉️ b'one\\ttwo\\nthree'
result = my_str.encode('unicode_escape').decode()
print(result) # 👉️ one\ttwo\nthree
str.encode
方法将字符串的编码版本作为字节对象返回。
bytes.decode
方法返回从给定字节解码的字符串。 默认编码是 utf-8。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。