如何在 Python 中將物件 x 轉換為字串形式?


Python 庫中最常用的 str() 函式返回物件的字串形式。

>>> no=100
>>> str(no)
'100'
>>> L1=[1,2,3,4]
>>> str(L1)
'[1, 2, 3, 4]'
>>> d={'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> str(d)
"{'a': 1, 'b': 2, 'c': 3, 'd': 4}"

但是,repr() 返回物件的預設且明確的表示形式,而 str() 會給出可讀且可能並不總是明確的非正式表示形式。

>>> str(d)
"{'a': 1, 'b': 2, 'c': 3, 'd': 4}"
>>> repr(d)
"{'a': 1, 'b': 2, 'c': 3, 'd': 4}"
>>> repr(L1)
'[1, 2, 3, 4]'
>>> repr(no)
'100'


更新於: 2020 年 2 月 24 日

231 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.