Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting raw strings python [duplicate]

Tags:

python

string

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?

like image 424
dave Avatar asked Mar 11 '10 19:03

dave


2 Answers

Python 3:

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

Python 2:

"hurr..\n..durr".encode('string-escape') 
like image 181
Ignacio Vazquez-Abrams Avatar answered Sep 29 '22 10:09

Ignacio Vazquez-Abrams


Yet another way:

>>> s = "hurr..\n..durr" >>> print repr(s).strip("'") hurr..\n..durr 
like image 35
Seth Avatar answered Sep 29 '22 11:09

Seth