在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、转换自定义对象为字符串:
如果自定义对象定义了__str__()
方法,则可以使用str()
函数将其转换为字符串,否则,会调用该对象的__repr__()
方法来生成一个表示该对象的字符串,示例如下:
“`python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person(‘{self.name}’, {self.age})"
def __repr__(self):
return f"<Person(‘{self.name}’, {self.age})>"
pass
p = Person("Alice", 25)
str_p = str(p) # 使用__str__()方法转换为字符串
print(type(str_p)) # <class ‘str’>
print(str_p) # "Person(‘Alice’, 25)"
“`
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/646331.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复