Susahrut
Susahrut

Reputation: 11

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

Upvotes: 0

Views: 899

Answers (2)

Arun Augustine
Arun Augustine

Reputation: 1766

%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)'

Upvotes: 0

Harshit Garg
Harshit Garg

Reputation: 2259

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

Upvotes: 1

Related Questions