Python 硬核教程 - 练习 6 - %r 与 %s 的区别

43 投票
7 回答
63578 浏览
提问于 2025-04-17 10:58

http://learnpythonthehardway.org/book/ex6.html

Zed在这里似乎把%r%s混用,这两者之间有什么区别吗?为什么不一直使用%s呢?

另外,我不太确定在文档中该搜索什么来找到更多信息。这%r%s到底叫什么?是格式化字符串吗?

7 个回答

3

下面是前面三个代码示例的总结。

# First Example
s = 'spam'
# "repr" returns a printable representation of an object,
# which means the quote marks will also be printed.
print(repr(s))
# 'spam'
# "str" returns a nicely printable representation of an
# object, which means the quote marks are not included.
print(str(s))
# spam

# Second Example.
x = "example"
print ("My %r" %x)
# My 'example'
# Note that the original double quotes now appear as single quotes.
print ("My %s" %x)
# My example

# Third Example.
x = 'xxx'
withR = ("Prints with quotes: %r" %x)
withS = ("Prints without quotes: %s" %x)
print(withR)
# Prints with quotes: 'xxx'
print(withS)
# Prints without quotes: xxx
21

%r 会调用 repr,而 %s 会调用 str。这两者在某些类型上可能表现得不一样,但在其他类型上则可能是一样的:repr 返回的是“对象的可打印表示”,而 str 返回的是“一个好看的可打印表示”。举个例子,对于字符串来说,它们的表现是不同的:

>>> s = "spam"
>>> print(repr(s))
'spam'
>>> print(str(s))
spam

在这个例子中,repr 是字符串的字面表示(Python 解释器可以把它解析成一个 str 对象),而 str 则只是字符串的内容。

67

它们被称为 字符串格式化操作

%s 和 %r 的区别在于,%s 使用的是 str 函数,而 %r 使用的是 repr 函数。你可以在 这个回答 中了解 strrepr 之间的区别,但对于内置类型来说,最明显的区别是 repr 输出的字符串会包含引号,并且所有特殊字符都会被转义。

撰写回答