Python 中TypeError: decoding str is not supported 错误
当我们尝试多次将对象转换为字符串或在调用 str()
类时设置编码关键字参数而不提供字节对象时,会出现 Python“TypeError: decoding str is not supported”。
看下面的代码
# ⛔️ TypeError: decoding str is not supported
str('hello', str(123))
# ⛔️ TypeError: decoding str is not supported
str('abc', encoding='utf-8')
第一个示例对
str()
函数进行了两次调用,一个嵌套在另一个中。在第二个示例中,我们在不提供有效字节对象的情况下设置了编码关键字参数。
我们只能在传递有效字节对象时设置编码。
print(str(b'abc', encoding='utf-8')) # 👉️ "abc"
如果需要连接字符串,请使用加法 +
运算符。
print('abc' + str(123)) # 👉️ "abc123"
加法 +
运算符可用于连接字符串。
或者,我们可以使用格式化的字符串文字。
str_1 = 'abc'
num_1 = 123
result = f'{str_1} {num_1}'
print(result) # 👉️ 'abc 123'
格式化字符串文字
f-strings
让我们通过在字符串前加上 f 来在字符串中包含表达式。
确保将表达式用大括号括起来 - {expression}
。
“TypeError: decoding str is not supported”错误消息意味着我们正在尝试以某种方式解码 str。
由于字符串已经从字节对象中解码出来,因此我们需要删除任何试图解码它的代码。
这是一个将字符串编码为字节并将字节对象解码回字符串的简单示例。
my_bytes = 'hello world'.encode('utf-8')
print(my_bytes) # 👉️ b'hello world'
my_str = my_bytes.decode('utf-8')
print(my_str) # 👉️ "hello world"
str.encode()
方法将字符串的编码版本作为字节对象返回。 默认编码是utf-8。
bytes.decode()
方法返回从给定字节解码的字符串。 默认编码是utf-8。
总结
当我们尝试多次将对象转换为字符串或在调用 str()
类时设置编码关键字参数而不提供字节对象时,会出现 Python“TypeError: decoding str is not supported”。
相关文章
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 日期时间。