简体   繁体   中英

Python print string with unicode escape characters

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

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

>>> Pedro León

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

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'

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

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

Output: Pedro Le\\\ón

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 \\

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM