簡體   English   中英

帶有unicode轉義字符的Python打印字符串

[英]Python print string with unicode escape characters

我正在嘗試打印“Pedro Le\ón”的文字 unicode 轉義字符。 當我執行以下操作時:

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

>>> Pedro León

我怎樣才能讓它輸出“Pedro Le\ón”?

使用unicode_escape encoding編碼為字節,然后立即解碼:

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

請注意,它是\\xXX轉義而不是\\uXXXX轉義,因為它小於 U+FF。 比較:

>>> '\u0080'
'\x80'

您需要使用原始字符串。 只需在字符串前使用r

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

輸出: Pedro Le\\\ón

試試這個

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

這是因為在 python 中有許多“特殊字符,如” '\\n' 等等,如果你想忽略它,你需要寫 \\\\ 而不是 \\

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM