Python repr() 函数用于返回对象的可复现表示,通常带引号,用于调试。
语法
repr(obj)参数
obj:任意对象。
返回值
返回对象的可复现字符串表示 str(通常带引号,用于调试)。
示例
s = "hello"
print(str(s)) # hello(给人看)
print(repr(s)) # 'hello'(带引号,程序员看)
print(str(42)) # 42
print(repr(42)) # 42
print(repr([1, 2])) # [1, 2]
print(repr("\n")) # '\n',显示转义
print(repr("a\nb")) # 'a\nb',能看到换行转义输出:
hello
'hello'
42
42
[1, 2]
'\n'
'a\nb'注意事项
str() 给人看,repr() 给程序看(力求 eval 能还原)。调试打印对象用 repr 能看到类型细节。f-string 里 f"{x!r}" 用 repr 表示。