[英]How to convert UTF-8 notation to python unicode notation
使用 python3.8 我想将 unicode 表示法转换为 python 表示法:
s = 'U+00A0'
result = s.lower() # output 'u+00a0'
我想用
\\u\u003c/code>替换
u+
:
result = s.lower().replace('u+','\u')
但我得到了错误:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape
如何将符号
U+00A0
转换为\
?
编辑:
我想获得
\
的原因是进一步使用encode
方法来获得b'\\xc2\\xa0'
。
我的问题:给定以下符号
U+00A0
的字符串,我想将其转换为字节码b'\\xc2\\xa0'
您正在为某物的表现与它的价值而苦苦挣扎……
import re
re.sub("u\+([0-9a-f]{4})",lambda m:chr(int(m.group(1),16)),s)
但对于 u+00a0 这变成 \\xa0
但与文字 \ 相同
s = "\u00a0"
print(repr(s))
一旦您将正确的值作为 unicode 字符串,您就可以将其编码为 utf8
s = "\xa0"
print(s.encode('utf8'))
# b'\xc2\xa0'
所以这里只是最后的答案
import re
s = "u+00a0"
s2 = re.sub("u\+([0-9a-f]{4})",lambda m:chr(int(m.group(1),16)),s)
s_bytes = s2.encode('utf8') # b'\xc2\xa0'
你也可以使用这个:
>>> s = 'U+00A0'
>>> s = s.replace('U+', '\\u').encode().decode('unicode_escape').encode()
>>> s
b'\xc2\xa0'
您需要转义\\
以replace
第二个\\
:
result = s.lower().replace('u+','\\u')
print(result)
会给你\
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.