Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python str()函数的功能和用法

作者:稍纵即逝   发布日期:2026-04-06   浏览:105

# 示例代码:使用 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字符串反转

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站