[python] Print raw string from variable? (not getting the answers)

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

This question is related to python string printing return

The answer is


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  
>>>   

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)

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)

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

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

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

  • re.sub(r"\", "/", x)
  • re.sub(r"\", "/", x)

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'

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.


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.


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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to printing

How do I print colored output with Python 3? Print a div content using Jquery Python 3 print without parenthesis How to find integer array size in java Differences Between vbLf, vbCrLf & vbCr Constants Printing variables in Python 3.4 Show DataFrame as table in iPython Notebook Removing display of row names from data frame Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window Print a div using javascript in angularJS single page application

Examples related to return

Method Call Chaining; returning a pointer vs a reference? How does Python return multiple values from a function? Return multiple values from a function in swift Python Function to test ping Returning string from C function "Missing return statement" within if / for / while Difference between return 1, return 0, return -1 and exit? C# compiler error: "not all code paths return a value" How to return a struct from a function in C++? Print raw string from variable? (not getting the answers)