迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

在 Python 中打印原始字符串(带有转义字符)

作者:迹忆客 最近更新:2023/01/09 浏览次数:

使用 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

在 Python 中打印原始字符串

第一个示例使用 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

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便