42

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 I'm after:

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

print(line1 == line2)  # outputs False
print(("%r"%line1)[1:-1] == line2)  # 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 kind of thing?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
dave
  • 485
  • 1
  • 5
  • 6
  • The reason you can't "cast" into a raw string is that there **aren't** "raw strings"; there are raw string **literals**, which are **only** a *different syntax for creating strings*. The data is the **same type**: `str`. The question is really about how to convert sequences *of text* in the original string, into *other sequences of text*. – Karl Knechtel Aug 08 '22 at 01:59

3 Answers3

82

Python 3:

"hurr..\n..durr".encode('unicode-escape').decode()

Python 2:

"hurr..\n..durr".encode('string-escape')
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

Yet another way:

>>> s = "hurr..\n..durr"
>>> print repr(s).strip("'")
hurr..\n..durr
Seth
  • 45,033
  • 10
  • 85
  • 120
  • 1
    That won't work if `s` has a `'` in it – John La Rooy 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 01:01
  • @Seth No, it will not, because if you have `'` contained in the data then the repr will have used double quotes instead of single quotes at the edges of the string. – wim Oct 11 '18 at 03:05
1

Above it was shown how to encode.

'hurr..\n..durr'.encode('string-escape')

This way will decode.

r'hurr..\n..durr'.decode('string-escape')

Ex.

In [12]: print 'hurr..\n..durr'.encode('string-escape')
hurr..\n..durr

In [13]: print r'hurr..\n..durr'.decode('string-escape')
hurr..
..durr

This allows one to "cast/trasform raw strings" in both directions. A practical case is when the json contains a raw string and I want to print it nicely.

{
    "Description": "Some lengthy description.\nParagraph 2.\nParagraph 3.",
    ...
}

I would do something like this.

print json.dumps(json_dict, indent=4).decode('string-escape')
Al Conrad
  • 1,528
  • 18
  • 12