如何在 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'

更新日期: 2019 年 3 月 30 日

189 次瀏覽

開啟 職業生涯

完成課程認證

立即開始
廣告