1

How to print strings escaped?

Example:

text_str = "żółć"
text_unicode = u"żółć"

print function(text_str)
'\xc5\xbc\xc3\xb3\xc5\x82\xc4\x87'
print function(text_unicode)
u'\u017c\xf3\u0142\u0107'

so, what function should I use?

updated I need more than escape, because I need this in log, and throwing escaped sometimes leads me to unescaped results

0

1 Answer 1

2

You want the repr output:

In [1]: text_str = "żółć"

In [2]: text_unicode = u"żółć"

In [3]: print repr(text_str)
'\xc5\xbc\xc3\xb3\xc5\x82\xc4\x87'

In [4]: print repr(text_unicode)
u'\u017c\xf3\u0142\u0107'

There are also 'string_escape' and 'unicode_escape':

text_str = "żółć"
text_unicode = u"żółć"

print text_str.encode('string_escape')

print text_unicode.encode('unicode_escape')

But encoding 'unicode_escape' will give you a str not unicode

Sign up to request clarification or add additional context in comments.

3 Comments

note this does not work in python 3.x, where repr("żółć") is żółć", however text_str.encode('unicode_escape') still works, although it returns a byte object
string_escape/unicode_escape are different functions - i need ONE function for both variants.
I'm checking if repr is ok, but for now i wonder how to escape the escaped ;) because print is ok, but debug - shows unescaped....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.