casting raw strings 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 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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Python 3:

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

Python 2:

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

Method 2

Yet another way:

>>> s = "hurr..n..durr"
>>> print repr(s).strip("'")
hurr..n..durr

Method 3

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x