Home > Backend Development > Python Tutorial > A brief introduction to %r and %s in Python

A brief introduction to %r and %s in Python

PHPz
Release: 2017-04-02 13:32:08
Original
1713 people have browsed it

%r uses the rper() method to process the object

%s uses the str() method to process the object

In some cases, the results of the two processes are the same For example, dealing with int type 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:

2014-04-14  
datetime.date(2014, 4, 14)
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 A brief introduction to %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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template