Home >Backend Development >Python Tutorial >Compare the usage differences between %r and %s in Python

Compare the usage differences between %r and %s in Python

巴扎黑
巴扎黑Original
2017-09-19 11:01:492206browse

%r uses the rper() method to process objects

%s uses the str() method to process objects

The function str() is used to convert values ​​into a form suitable for human reading. Repr() converts it into a form for the interpreter to read (if there is no equivalent syntax, a SyntaxError exception will occur). If an object does not have an interpretation form suitable for human reading, str() will return the equivalent of repr(). value. Many types, such as numerical values ​​or structures such as linked lists and dictionaries, have a unified interpretation method for each function.

In some cases, the results of the two processes are the same, such as processing int objects.

Example 1:

print "I am %d years old." % 22
print "I am %s years old." % 22
print "I am %r years old." % 22

Return result:

I am 22 years old.
I am 22 years old.
I am 22 years old.

In other cases, the two are different

Example 2:

text = "I am %d years old." % 22
print "I said: %s." % text
print "I said: %r." % text

Return result:

I said: I am 22 years old..
I said: 'I am 22 years old.'.   #%r 给字符串加了单引号

Look at another situation

Example 3:

import datetime
d = datetime.date.today()
print "%s" % d
print "%r" % d

Return result:

2017-08-16
datetime.date(2017, 8, 16)

It can be seen that %r can be reproduced when printing The object it represents (rper() unambiguously recreate the object it represents)

The above is the detailed content of Compare the usage differences between %r and %s in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn