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

巴扎黑
Release: 2017-09-19 11:01:49
Original
2067 people have browsed it

%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
Copy after login

Return result:

I am 22 years old. I am 22 years old. I am 22 years old.
Copy after login

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
Copy after login

Return result:

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

Look at another situation

Example 3:

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

Return result:

2017-08-16 datetime.date(2017, 8, 16)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!