迹忆客 专注技术分享

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

在 Python 中将字符串转换为原始字符串

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

要将字符串转换为原始字符串:

  1. 使用 str.encode() 方法将字符串转换为字节对象。
  2. 使用 bytes.decode() 方法将字节对象转换为原始字符串。
my_str = 'one\ttwo\nthree'

print(repr(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

python 字符串转换为原始字符串

我们使用 str.encode() 方法将字符串转换为带有转义字符的字节对象。

str.encode 方法将字符串的编码版本作为字节对象返回。 默认编码为 utf-8

my_str = 'one\ttwo\nthree'

my_bytes = my_str.encode('unicode_escape')
print(my_bytes)  # 👉️ b'one\\ttwo\\nthree'

my_bytes = my_str.encode()
print(my_bytes)  # 👉️ b'one\ttwo\nthree'

Python 中将字符串转换为原始字符串默认编码

注意 ,当我们使用 unicode_escape 编码时,会添加一个额外的反斜杠。

使用 bytes.decode() 方法将字节对象转换为字符串。

my_str = 'one\ttwo\nthree'


result = my_str.encode('unicode_escape').decode()
print(result)  # 👉️ one\ttwo\nthree

bytes.decode() 方法返回从给定字节解码的字符串。 默认编码为 utf-8

编码是将字符串转换为字节对象的过程,解码是将字节对象转换为字符串的过程。

如果我们有权访问变量的声明,则可以在字符串前面加上 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。

转载请发邮件至 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便