MST

星途 面试题库

面试题:Python基本类型函数之中等难度题

请阐述Python中`str()`函数和`repr()`函数在处理基本类型数据时的主要区别,并举例说明。
37.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

主要区别

  1. 用途
    • str() 函数的目标是返回一个人类可读的字符串表示,通常用于向用户展示数据。
    • repr() 函数的目标是返回一个可以用来重新创建对象的字符串表示,更侧重于开发调试,给开发者看。
  2. 输出格式
    • 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() 提供了更友好的用户展示信息。