This article describes the difference between %r and %s in Python
%r is the object processed by the rper() method
%s is the object processed by the str() method
In fact, in some cases, the results of the two processes are the same, for example, the data type is an int type object;
For example 1:
print ('I am %d year old.' % 22)
print ('I am %s year old.' % 22)
print ('I am %r year old.' % 22)
Returned result:
I am 22 year old.
I am 22 year old.
I am 22 year old.
In addition, there are some situations where the two are different
For example 2:
test = 'I am %d year old.' % 22 #test is printed in the form of a string;
print ('I said: %s' % test)
print ('I said: %r' % test)
Returned result:
I said: I am 22 year old.
I said: 'I am 22 year old.'#%r adds single quotes to the string;
Let’s look at another situation:
For example 3:
d = datetime.date.tody()
print ('%s' % d)
print(' %r' % r)
Returned result:
2017-03-16
datetime.date(2017, 3, 16)
Yes See, %r can reproduce the object it represents when printing
ps: The analysis may not be sufficient. Blog friends can share and learn if they have detailed information;
The above is the detailed content of An introduction to the difference between %r and %s in Python. For more information, please follow other related articles on the PHP Chinese website!