【发布时间】:2012-02-17 15:52:01
【问题描述】:
http://learnpythonthehardway.org/book/ex6.html
Zed 在这里似乎可以互换使用%r 和%s,这两者有什么区别吗?为什么不一直使用%s?
另外,我不确定要在文档中搜索什么才能找到有关此的更多信息。 %r 和 %s 到底叫什么?格式化字符串?
【问题讨论】:
标签: python
http://learnpythonthehardway.org/book/ex6.html
Zed 在这里似乎可以互换使用%r 和%s,这两者有什么区别吗?为什么不一直使用%s?
另外,我不确定要在文档中搜索什么才能找到有关此的更多信息。 %r 和 %s 到底叫什么?格式化字符串?
【问题讨论】:
标签: python
%s 调用str(),而%r 调用repr()。详情见Difference between __str__ and __repr__ in Python
【讨论】:
他们被称为string formatting operations。
%s 和 %r 的区别在于 %s 使用 str 函数,而 %r 使用 repr 函数。您可以在this answer 中了解str 和repr 之间的区别,但是对于内置类型,实践中最大的区别是repr 的字符串包含引号并且所有特殊字符都被转义。
【讨论】:
下面的代码说明了不同之处。相同的值打印不同:
x = "xxx"
withR = "prints with quotes %r"
withS = "prints without quotes %s"
【讨论】:
x = "example"
print "My %s"%x
My example
print "My %r"%x
My 'example'
上面的答案很好地解释了。我试图用一个简单的例子来证明这一点。
【讨论】:
以下是对前面三个代码示例的总结。
# 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
【讨论】:
%s => 字符串
%r => 完全一样
使用书中的代码:
my_name = 'Zed A. Shaw'
print "Let's talk about %s." % my_name
print "Let's talk about %r." % my_name
我们得到
Let's talk about Zed A. Shaw.
Let's talk about 'Zed A. Shaw'.
【讨论】: