0

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
Shadow
  • 8,749
  • 4
  • 47
  • 57
Susahrut
  • 11
  • 2
  • The answer is more clearly given here.(https://stackoverflow.com/questions/2354329/whats-the-meaning-of-r-in-python) – Rangeesh Jul 03 '19 at 05:15

2 Answers2

1

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
Harshit Garg
  • 2,137
  • 21
  • 23
0

%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)'
Arun Augustine
  • 1,690
  • 1
  • 13
  • 20