# 示例代码:使用 str() 函数将不同类型的对象转换为字符串
# 将整数转换为字符串
num = 123
str_num = str(num)
print(f"整数 {num} 转换为字符串: {str_num}") # 输出: 整数 123 转换为字符串: 123
# 将浮点数转换为字符串
float_num = 3.14
str_float = str(float_num)
print(f"浮点数 {float_num} 转换为字符串: {str_float}") # 输出: 浮点数 3.14 转换为字符串: 3.14
# 将布尔值转换为字符串
boolean = True
str_boolean = str(boolean)
print(f"布尔值 {boolean} 转换为字符串: {str_boolean}") # 输出: 布尔值 True 转换为字符串: True
# 将列表转换为字符串
list_example = [1, 2, 3]
str_list = str(list_example)
print(f"列表 {list_example} 转换为字符串: {str_list}") # 输出: 列表 [1, 2, 3] 转换为字符串: [1, 2, 3]
# 使用 str() 函数指定编码格式(适用于字节类型)
byte_data = b'hello'
str_byte = str(byte_data, encoding='utf-8')
print(f"字节数据 {byte_data} 转换为字符串: {str_byte}") # 输出: 字节数据 b'hello' 转换为字符串: hello
str() 函数用于将其他类型的对象转换为字符串。str(byte_data, encoding='utf-8') 指定编码格式进行转换。上一篇:python wheel
下一篇:python字符串反转
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站