92

I'm trying to find a way to print a string in raw form from a variable. For instance, if I add an environment variable to Windows for a path, which might look like 'C:\\Windows\Users\alexb\', I know I can do:

print(r'C:\\Windows\Users\alexb\')

But I cant put an r in front of a variable.... for instance:

test = 'C:\\Windows\Users\alexb\'
print(rtest)

Clearly would just try to print rtest.

I also know there's

test = 'C:\\Windows\Users\alexb\'
print(repr(test))

But this returns 'C:\\Windows\\Users\x07lexb' as does

test = 'C:\\Windows\Users\alexb\'
print(test.encode('string-escape'))

So I'm wondering if there's any elegant way to make a variable holding that path print RAW, still using test? It would be nice if it was just

print(raw(test))

But its not

David Buck
  • 3,752
  • 35
  • 31
  • 35
aescript
  • 1,775
  • 4
  • 20
  • 30
  • 1
    possible duplicate of [python : how to convert string literal to raw string literal?](http://stackoverflow.com/questions/7262828/python-how-to-convert-string-literal-to-raw-string-literal) – zero323 Sep 09 '13 at 21:32
  • 3
    `r'C:\Windows\Users\alexb\'` is actually a syntax error, by the way. – kindall Sep 09 '13 at 22:18

14 Answers14

58

I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answer that the solution lies with changing the string.

Two ways of solving it:

  1. Get the path you want using native python functions, e.g.:

    test = os.getcwd() # In case the path in question is your current directory
    print(repr(test))
    

    This makes it platform independent and it now works with .encode. If this is an option for you, it's the more elegant solution.

  2. If your string is not a path, define it in a way compatible with python strings, in this case by escaping your backslashes:

    test = 'C:\\Windows\\Users\\alexb\\'
    print(repr(test))
    
user2357112
  • 260,549
  • 28
  • 431
  • 505
OlavRG
  • 742
  • 6
  • 4
46

In general, to make a raw string out of a string variable, I use this:

string = "C:\\Windows\Users\alexb"

raw_string = r"{}".format(string)

output:

'C:\\\\Windows\\Users\\alexb'
Samer Alkhabbaz
  • 507
  • 5
  • 7
  • 1
    Interestingly this does not work for `\v` `>>> k = "\vsadfkjhkasdf\nasdfsadf"` `>>> r = r"{}".format(k)` `>>> r` `'\x0bsadfkjhkasdf\nasdfsadf'`` – malhar Feb 14 '19 at 23:57
  • this works for `variable = r"{}".format(another_variable)` like a magic – Alper Nov 16 '20 at 13:37
  • It does not work: ` str1 = 'dfdf\"dfdfd' str2 = r"{}".format(str1) print(str2) ` Output: dfdf"dfdfd – user07 Feb 04 '21 at 21:25
39

You can't turn an existing string "raw". The r prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10), by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.

  • 1
    I believe you really got the point. None of the above worked for me, when I needed to use `re` and variables in a `re.sub` call (with Windows paths, but is just a case among others). I solved (badly) re-escaping the strings: `path = r"c:\this\is\a\test.txt" ; part_to_be_changed = r"c:\this" ; part_to_be_changed_reescaped = re.sub("\\\\", "\\\\\\\\", part_to_be_changed) ; new_part = "d:\\this_really" ; new_part_reescaped = re.sub("\\\\", "\\\\\\\\", new_part) ; new_string = re.sub(part_to_be_changed_reescaped, new_part_reescaped, path) ; print(new_string) ; >> d:\this_really\is\a\test.txt` – shub Jul 25 '19 at 22:11
  • This should be the accepted answer. Or at least need to be part of it. https://www.pythontutorial.net/python-basics/python-raw-strings/ – geryxyz Feb 02 '23 at 11:02
14

I know i'm too late for the answer but for people reading this I found a much easier way for doing it

myVariable = 'This string is supposed to be raw \'
print(r'%s' %myVariable)
Jimmynoarms
  • 169
  • 1
  • 7
7

try this. Based on what type of output you want. sometime you may not need single quote around printed string.

test = "qweqwe\n1212as\t121\\2asas"
print(repr(test)) # output: 'qweqwe\n1212as\t121\\2asas'
print( repr(test).strip("'"))  # output: qweqwe\n1212as\t121\\2asas
kumar chandraketu
  • 2,232
  • 2
  • 20
  • 25
4

Get rid of the escape characters before storing or manipulating the raw string:

You could change any backslashes of the path '\' to forward slashes '/' before storing them in a variable. The forward slashes don't need to be escaped:

>>> mypath = os.getcwd().replace('\\','/')  
>>> os.path.exists(mypath)  
True  
>>>   
DrawT
  • 232
  • 4
  • 6
4

Just simply use r'string'. Hope this will help you as I see you haven't got your expected answer yet:

    test = 'C:\\Windows\Users\alexb\'
    rawtest = r'%s' %test
An Khang
  • 261
  • 2
  • 9
3

I have my variable assigned to big complex pattern string for using with re module and it is concatenated with few other strings and in the end I want to print it then copy and check on regex101.com. But when I print it in the interactive mode I get double slash - '\\w' as @Jimmynoarms said:

The Solution for python 3x:

print(r'%s' % your_variable_pattern_str)
Nick Po
  • 128
  • 7
  • great answer! works for me, however could you explain why this works and why the others don't? Is this a rendering problem in python?? – Farhan Hai Khan Jan 25 '22 at 15:52
1

Your particular string won't work as typed because of the escape characters at the end \", won't allow it to close on the quotation.

Maybe I'm just wrong on that one because I'm still very new to python so if so please correct me but, changing it slightly to adjust for that, the repr() function will do the job of reproducing any string stored in a variable as a raw string.

You can do it two ways:

>>>print("C:\\Windows\Users\alexb\\")

C:\Windows\Users\alexb\

>>>print(r"C:\\Windows\Users\alexb\\")
C:\\Windows\Users\alexb\\

Store it in a variable:

test = "C:\\Windows\Users\alexb\\"

Use repr():

>>>print(repr(test))
'C:\\Windows\Users\alexb\\'

or string replacement with %r

print("%r" %test)
'C:\\Windows\Users\alexb\\'

The string will be reproduced with single quotes though so you would need to strip those off afterwards.

1

To turn a variable to raw str, just use

rf"{var}"

r is raw and f is f-str; put them together and boom it works.

cottontail
  • 10,268
  • 18
  • 50
  • 51
0

Replace back-slash with forward-slash using one of the below:

  • re.sub(r"\", "/", x)
  • re.sub(r"\", "/", x)
dgor
  • 704
  • 6
  • 19
0

This does the trick

>>> repr(string)[1:-1]

Here is the proof

>>> repr("\n")[1:-1] == r"\n"
True

And it can be easily extrapolated into a function if need be

>>> raw = lambda string: repr(string)[1:-1]
>>> raw("\n")
'\\n'
-2

i wrote a small function.. but works for me

def conv(strng):
    k=strng
    k=k.replace('\a','\\a')
    k=k.replace('\b','\\b')
    k=k.replace('\f','\\f')
    k=k.replace('\n','\\n')
    k=k.replace('\r','\\r')
    k=k.replace('\t','\\t')
    k=k.replace('\v','\\v')
    return k
kakka
  • 9
-3

Here is a straightforward solution.

address = 'C:\Windows\Users\local'
directory ="r'"+ address +"'"

print(directory)

"r'C:\\Windows\\Users\\local'"
Abhijeet sinha
  • 403
  • 4
  • 4