[英]python string replace to \u
我有一个字符串。
m = 'I have two element. <U+2F3E> and <U+2F8F>'
我想替换为:
m = 'I have two element. \u2F3E and \u2F8F' # utf-8
我的代码:
import re
p1 = re.compile('<U+\+') # start "<"
p2 = re.compile('>+') # end ">"
m = 'I have two element. <U+2F3E> and <U+2F8F>'
out = pattern.sub('\\u', m) # like: 'I have two element. \u2F3E> and \u2F8F>'
但我收到此错误消息:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape
我该如何解决。 谢谢。
import re
m = 'I have two element. <U+2F3E> and <U+2F8F>'
print(re.sub(r'<U\+(\w+)>', r"\\u\1", m))
# I have two element. \u2F3E and \u2F8F
您可以使用单个正则表达式来查找字符串并拉出要在替换中使用的部分。
您收到错误的原因是
'\\\\u\u0026#39;
将文字字符串\\u\u003c/code>传递给正则表达式引擎,该引擎尝试将其解析为 Unicode 字符,但失败了;
\\u\u003c/code>需要紧跟四个十六进制数字以形成有效的 Unicode 代码点。
但是你仍然在接近这个,好像你想用一个文字字符串替换,根据你的澄清评论是错误的。
import re
m = re.sub(r'<U\+([0-9a-fA-F]{4})>', lambda x: chr(int(x.group(1), 16)), m)
lambda
接收匹配对象作为其参数; x.group(1)
取出第一个带括号的组, chr(int(that, 16))
产生相应的文字字符。
如果你真的想产生它的 UTF-8 编码,那也很容易:
>>> re.sub(r'<U\+([0-9a-fA-F]{4})>', lambda x: chr(int(x.group(1), 16)), 'I have two element. <U+2F3E> and <U+2F8F>')
'I have two element. ⼾ and ⾏'
>>> re.sub(r'<U\+([0-9a-fA-F]{4})>', lambda x: chr(int(x.group(1), 16)), 'I have two element. <U+2F3E> and <U+2F8F>').encode('utf-8')
b'I have two element. \xe2\xbc\xbe and \xe2\xbe\x8f'
如您所见,UTF-8 编码是一个字节序列,根本不对应于可打印字符。 (好吧,它们可以用其他一些编码打印;但那只是mojibake。)
m.replace('<U+', '\u')
m.replace('>',' ')
请使用下面的代码,这可能会有所帮助
m = m.replace('<U+', '\\u').replace('>',' ')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.