Fast
Fast

Reputation: 43

Python print string with unicode escape characters

I'm trying to print the literal unicode escape character of "Pedro Le\u00F3n". When I do the following:

test = "Pedro Le\u00F3n"
print(test)

>>> Pedro León

How can I get it to output "Pedro Le\u00F3n"?

Upvotes: 1

Views: 162

Answers (3)

colmo007
colmo007

Reputation: 38

You need to use raw strings. Simply use r before your string:

test = r"Pedro Le\\u00F3n"
print(test)

Output: Pedro Le\\u00F3n

Upvotes: 1

wjandrea
wjandrea

Reputation: 32928

Encode to bytes with the unicode_escape encoding, and decode right back:

>>> out = test.encode('unicode_escape').decode()
>>> out
'Pedro Le\\xf3n'
>>> print(out)
Pedro Le\xf3n

Note that it's a \xXX escape instead of a \uXXXX escape, since it's less than U+FF. For comparison:

>>> '\u0080'
'\x80'

Upvotes: 2

ori ofek
ori ofek

Reputation: 21

try this

test = "Pedro Le\\u00F3n"
print(test)

it causes because in python there are many "special characters like" '\n' and more and if you want to ignore it you need to write \ \ instead of \

Upvotes: 0

Related Questions