简体   繁体   中英

What does %r do in a format string?

I was doing a code to accept some file path as command line argument and then wanted to see what %r does... I tried few things, please go through the following code and let me know how exactly does the %r specifier works and why there is '\\' before p.

string1 = "C:\raint\new.txt"

string2 = "%r"%string1
string3 = string2[1:-1]

print "Input String: ",string2           
print "Raw String: ",string3  

string1 = "C:\raint\pint.txt"

string2 = "%r"%string1
string3 = string2[1:-1]

print "Input String: ",string2           
print "Raw String: ",string3            

Output:

Input String: 'C:\raint\new.txt'
Raw String: C:\raint\new.txt
Input String: 'C:\raint\\pint.txt'
Raw String: C:\raint\\pint.txt

It is string formatter just as there are other formatters like %s for string, %d for integer. Essentially when you encounter a formatter like %s or %r, a specific method is called on that object. In case of %s, it str() method and in case of %r it is repr() method. Some good reference resources are:

  1. Diff between str and repr
  2. Python3 doc
  3. Related stuff for formatters

%r does the conversion using repr() function. It returns exact representation of object. Using repr() most of the data types have the similar output, but we can find the difference below.

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2019, 7, 3)
>>> str(date)
'2019-07-03'
>>> repr(date)
'datetime.date(2019, 7, 3)'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM