首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python的艰难之路-练习6- %r与%s

Python的艰难之路-练习6- %r与%s
EN

Stack Overflow用户
提问于 2012-01-24 19:37:39
回答 7查看 62.6K关注 0票数 42

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

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

此外,我不确定要在文档中搜索什么才能找到有关这方面的更多信息。%r%s的确切名称是什么?格式化字符串?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2012-01-24 19:46:10

它们被称为string formatting operations

%s和%r之间的区别在于%s使用str函数,而%r使用repr函数。您可以在this answer中了解strrepr之间的区别,但是对于内置类型,实践中最大的区别是字符串的repr包括引号,并且所有特殊字符都被转义。

票数 65
EN

Stack Overflow用户

发布于 2012-01-24 19:39:33

%r调用repr,而%s调用str。对于某些类型,它们的行为可能不同,但对于其他类型则不同:repr返回“对象的可打印表示”,而str返回“对象的可打印表示”。例如,它们对于字符串是不同的:

代码语言:javascript
复制
>>> s = "spam"
>>> print(repr(s))
'spam'
>>> print(str(s))
spam

在本例中,repr是字符串的文字表示形式( Python解释器可以将其解析为str对象),而str只是字符串的内容。

票数 21
EN

Stack Overflow用户

发布于 2016-03-18 12:37:51

下面是前面三个代码示例的摘要。

代码语言:javascript
复制
# 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
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8986179

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档