如何在Python中将任何数据类型转换为字符串?
使用str()函数将任何内置数据类型转换为其字符串表示形式
>>> str(10)
'10'
>>> str(11.11)
'11.11'
>>> str(3+4j)
'(3+4j)'
>>> str([1,2,3])
'[1, 2, 3]'
>>> str((1,2,3))
'(1, 2, 3)'
>>> str({1:11, 2:22, 3:33})
'{1: 11, 2: 22, 3: 33}'
对于需要将用户定义的类转换为字符串表示形式的,需要在类中定义str()函数。
>>> class rectangle:
def __init__(self):
self.l=10
self.b=10
def __str__(self):
return 'length={} breadth={}'.format(self.l, self.b)
>>> r1=rect()
>>> str(r1)
'length = 10 breadth = 10'
极客教程