Take the 2-minute tour ×

in python, given a variable which holds a string is there a quick way to cast that into another raw string variable?

the following code should illustrate what im after...

def checkEqual(x, y):
    print True if x==y else False

line1 = "hurr..\n..durr"
line2 = r"hurr..\n..durr"
line3 = "%r"%line1

print "%s \n\n%s \n\n%s \n" % (line1, line2, line3)

checkEqual(line2, line3)        #outputs False

checkEqual(line2, line3[1:-1])  #outputs True

The closest I have found so far is the %r formatting flag which seems to return a raw string albeit within single quote marks. Is there any easier way to do this like a line3 = raw(line1) kind of thing?

share|improve this question
Please don't use the word "cast". Python doesn't have such a thing. You want to "transform" or "convert" a raw string into another string. "quick" has nothing to do with it either. –  S.Lott Mar 11 '10 at 20:05
checkEqual can simply be return x == y –  Schoolboy Aug 29 '13 at 5:39
Thanks @Schoolboy for pointing that out. It always burns me to see something as redundant as print True if True else False :/ –  OozeMeister Sep 17 '13 at 15:38
add comment

4 Answers

up vote 31 down vote accepted
share|improve this answer
nice one. str.encode() with the various codecs is exactly what i was after. 'unicode-escape' actually solves another problem i was having too. cheers –  dave Mar 11 '10 at 20:14
This doesn't work for \w etc. –  gnibbler Mar 11 '10 at 21:04
I'm getting an error in Python3.3 LookupError: unknown encoding: string-escape –  Erik Apr 1 '13 at 20:16
@Erik, strings in Python 3 are Unicode, use unicode-escape. –  Mark Tolonen Jun 27 '13 at 3:11
add comment

Ok, there apparently is an easier way. I'll leave this solution in for comparison sake.


def raw(text):
    """Returns a raw string representation of text"""
    for char in text:
        try: new_string+=escape_dict[char]
        except KeyError: new_string+=char
    return new_string
share|improve this answer
add comment

Yet another way:

>>> s = "hurr..\n..durr"
>>> print repr(s).strip("'")
share|improve this answer
That won't work if s has a ' in it –  gnibbler Mar 11 '10 at 21:07
It should be ok if the ' is in the middle of the string, but it's definitely not robust (it's screwy with Unicode strings, for example). –  Seth Mar 12 '10 at 1:01
add comment
>>> v1 = 'aa\1.js'
>>> re.sub(r'(.*)\.js', repr(v1).strip("'"), 'my.js', 1)


>>> re.sub(r'(.*)\.js', r'aa\1.js', 'my.js', 1)


>>> re.sub(r'(.*)\.js', raw(v1), 'my.js', 1)

And better raw method implementation

def raw(text):
    return "".join([escape_dict.get(char,char) for char in text])
share|improve this answer
add comment

Your Answer


