python里str函数怎么用
- 行业动态
- 2024-05-23
- 2
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}"
“`
本站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本站,有问题联系侵删!
本文链接:http://www.xixizhuji.com/fuzhu/200048.html