Python - String Raw Strings


The raw strings have the following syntax:

r'your string'

If the letter r (uppercase or lowercase) appears just before the opening quote of a string.

It turns off the escape mechanism.

Python retains your backslashes literally, exactly as you type them in raw string.

myfile = open(r'C:\new\text.dat', 'w') 
--two backslashes are an escape sequence for one backslash, 
myfile = open('C:\\new\\text.dat', 'w') 

Python itself sometimes uses this doubling scheme when it prints strings with embedded backslashes:


path = r'C:\new\text.dat' 
print( path )                          # Show as Python code 
print(path)                   # User-friendly format 
print( len(path) )                     # String length
# from w  w w.j  a va2