Python putting r before unicode string variable -


for static strings, putting r in front of string give raw string (e.g. r'some \' string'). since not possible put r in front of unicode string variable, minimal approach dynamically convert string variable raw form? should manually substitute backslashes double backslashes?

str_var = u"some text escapes e.g. \( \' \)" raw_str_var = ??? 

if need escape string, let's want print newline \n, can use encode method python specific string_escape encoding:

>>> s = "hello\nworld" >>> e = s.encode("string_escape") >>> e "hello\\nworld" >>> print s hello world >>> print e hello\nworld 

you didn't mention unicode, or python version using, if dealing unicode strings should use unicode_escape instead.

>>> u = u"föö\nbär" >>> print u föö bär >>> print u.encode('unicode_escape') f\xf6\xf6\nb\xe4r 

your post had regex tag, maybe re.escape you're looking for?

>>> re.escape(u"foo\nbar\'baz") u"foo\\\nbar\\'baz" 

not "double escapes", ie printing above string yields:

foo\ bar\'baz 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -