在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}"
“`
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/649449.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复