简体   繁体   English

Python强制Unicode转义

[英]Python enforce unicode escape

how do I enforce unicode escape in python? 如何在python中执行unicode转义?

I have the unicode string u'aä' or u'a\ä' and I want it to be represented as a\ä . 我有unicode字符串u'aä'u'a\ä'并且希望将其表示为a\ä The solution suggested here doesn't work for me: 这里建议的解决方案对我不起作用:

>>> repr(u'a\u00e4')
"u'a\\xe4'"

From my understanding the following attempt should be the correct solution (but isn't): 据我了解,以下尝试应该是正确的解决方案(但不是):

>>> u'a\u00e4'.encode('unicode-escape')
'a\\xe4'

I tried it with python 2.6 and 2.7 on OS X and with 2.6 on Debian Squeeze. 我在OS X上使用python 2.6和2.7以及在Debian Squeeze上使用2.6进行了尝试。

Thanks for your time. 谢谢你的时间。

Unicode characters below 256 are always encoded with \\x in their repr() esentation, as it is the least space-consuming. 小于256的Unicode字符在其repr()表示中始终使用\\x进行编码,因为它占用的空间最少。

Nevertheless, they are unicode because of the u' at the start. 但是,由于开头是u' ,所以它们是unicode。 It is just a matter of representation. 这只是代表问题。

If you want it nevertheless, you could do 如果您仍然想要,可以

print repr(u'a\u00e4').replace('\\x','\\u00')

.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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