Python 硬核教程 - 练习 6 - %r 与 %s 的区别
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