当前位置:首页 > 行业动态 > 正文

python里str函数怎么用

str函数用于将其他数据类型转换为字符串类型。使用方法为:str(数据类型),str(123)。

在Python中,str()函数用于将其他类型的数据转换为字符串类型,下面是关于str()函数的详细用法:

1、转换整数为字符串:

“`python

num = 123

str_num = str(num)

print(type(str_num)) # <class ‘str’>

print(str_num) # ‘123’

“`

2、转换浮点数为字符串:

“`python

float_num = 3.14

str_float = str(float_num)

print(type(str_float)) # <class ‘str’>

print(str_float) # ‘3.14’

“`

3、转换布尔值为字符串:

“`python

bool_value = True

str_bool = str(bool_value)

print(type(str_bool)) # <class ‘str’>

print(str_bool) # ‘True’

“`

4、转换列表为字符串:

“`python

lst = [1, 2, 3]

str_lst = str(lst)

print(type(str_lst)) # <class ‘str’>

print(str_lst) # "[1, 2, 3]"

“`

5、转换元组为字符串:

“`python

tup = (4, 5, 6)

str_tup = str(tup)

print(type(str_tup)) # <class ‘str’>

print(str_tup) # "(4, 5, 6)"

“`

6、转换字典为字符串:

“`python

dict_obj = {‘name’: ‘John’, ‘age’: 25}

str_dict = str(dict_obj)

print(type(str_dict)) # <class ‘str’>

print(str_dict) # "{‘name’: ‘John’, ‘age’: 25}"

“`

7、转换集合为字符串:

“`python

set_obj = {1, 2, 3}

str_set = str(set_obj)

print(type(str_set)) # <class ‘str’>

print(str_set) # "{1, 2, 3}"

“`

0