面试题答案
一键面试主要区别
- 用途:
str()
函数的目标是返回一个人类可读的字符串表示,通常用于向用户展示数据。repr()
函数的目标是返回一个可以用来重新创建对象的字符串表示,更侧重于开发调试,给开发者看。
- 输出格式:
str()
的输出通常是简洁、易读的。repr()
的输出尽可能精确,会包含一些有助于重建对象的信息,如引号等。
举例说明
num = 10
# str() 示例
print(str(num))
# 输出: 10
# repr() 示例
print(repr(num))
# 输出: 10
s = 'Hello, World!'
# str() 示例
print(str(s))
# 输出: Hello, World!
# repr() 示例
print(repr(s))
# 输出: 'Hello, World!'
在处理字符串时,repr()
会保留引号,而 str()
则直接输出字符串内容,在处理数字时,两者输出类似,但对于更复杂的数据类型,差异会更明显。例如:
lst = [1, 2, 3]
# str() 示例
print(str(lst))
# 输出: [1, 2, 3]
# repr() 示例
print(repr(lst))
# 输出: [1, 2, 3]
class MyClass:
def __init__(self, value):
self.value = value
def __repr__(self):
return f'MyClass({self.value})'
def __str__(self):
return f'Object with value {self.value}'
obj = MyClass(42)
# str() 示例
print(str(obj))
# 输出: Object with value 42
# repr() 示例
print(repr(obj))
# 输出: MyClass(42)
从类的例子可以看出,repr()
提供了可以重建对象的信息,而 str()
提供了更友好的用户展示信息。