如何在 Python 中将对象 x 转换为字符串表示?

pythonserver side programmingprogramming更新于 2025/7/20 6:36:17

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'



相关文章


有用资源