http://learnpythonthehardway.org/book/ex6.html
Zed似乎在这里交替使用了%r和%s,这两者之间有什么区别吗?为什么不一直使用%s呢?
此外,我不确定要在文档中搜索什么才能找到有关这方面的更多信息。%r和%s的确切名称是什么?格式化字符串?
发布于 2012-01-24 19:46:10
它们被称为string formatting operations。
%s和%r之间的区别在于%s使用str函数,而%r使用repr函数。您可以在this answer中了解str和repr之间的区别,但是对于内置类型,实践中最大的区别是字符串的repr包括引号,并且所有特殊字符都被转义。
发布于 2012-01-24 19:39:33
%r调用repr,而%s调用str。对于某些类型,它们的行为可能不同,但对于其他类型则不同:repr返回“对象的可打印表示”,而str返回“对象的可打印表示”。例如,它们对于字符串是不同的:
>>> s = "spam"
>>> print(repr(s))
'spam'
>>> print(str(s))
spam在本例中,repr是字符串的文字表示形式( Python解释器可以将其解析为str对象),而str只是字符串的内容。
发布于 2016-03-18 12:37:51
下面是前面三个代码示例的摘要。
# 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: xxxhttps://stackoverflow.com/questions/8986179
复制相似问题