tags:

views:

164

answers:

3

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?

+7  A: 
"hurr..\n..durr".encode('string-escape')
Ignacio Vazquez-Abrams
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
This doesn't work for `\w` etc.
gnibbler
A: 

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

escape_dict={'\a':r'\a',
           '\b':r'\b',
           '\c':r'\c',
           '\f':r'\f',
           '\n':r'\n',
           '\r':r'\r',
           '\t':r'\t',
           '\v':r'\v',
           '\'':r'\'',
           '\"':r'\"',
           '\0':r'\0',
           '\1':r'\1',
           '\2':r'\2',
           '\3':r'\3',
           '\4':r'\4',
           '\5':r'\5',
           '\6':r'\6',
           '\7':r'\7',
           '\8':r'\8',
           '\9':r'\9'}

def raw(text):
    """Returns a raw string representation of text"""
    new_string=''
    for char in text:
        try: new_string+=escape_dict[char]
        except KeyError: new_string+=char
    return new_string
Pierre-Antoine LaFayette
A: 

Yet another way:

>>> s = "hurr..\n..durr"
>>> print repr(s).strip("'")
hurr..\n..durr
Seth
That won't work if `s` has a `'` in it
gnibbler
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