今天碰到一個很有意思的問題,需要將普通的 Unicode字符串轉(zhuǎn)換為 Unicode編碼的字符串,如下:
將 //u9500//u552e 轉(zhuǎn)化為 /u9500/u552e 也就是 銷售 。
乍一看感覺挺簡單的,用 re 庫將前面的反斜杠去掉即可,但是在替換的過程中會拋出如下錯誤:
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
re.sub(r"(/)/u", r'', t)
File "D:/Python36/lib/re.py", line 191, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "D:/Python36/lib/re.py", line 301, in _compile
p = sre_compile.compile(pattern, flags)
File "D:/Python36/lib/sre_compile.py", line 562, in compile
p = sre_parse.parse(p, flags)
File "D:/Python36/lib/sre_parse.py", line 855, in parse
p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
File "D:/Python36/lib/sre_parse.py", line 416, in _parse_sub
not nested and not items))
File "D:/Python36/lib/sre_parse.py", line 765, in _parse
p = _parse_sub(source, state, sub_verbose, nested + 1)
File "D:/Python36/lib/sre_parse.py", line 416, in _parse_sub
not nested and not items))
File "D:/Python36/lib/sre_parse.py", line 502, in _parse
code = _escape(source, this, state)
File "D:/Python36/lib/sre_parse.py", line 362, in _escape
raise source.error("incomplete escape %s" % escape, len(escape))
sre_constants.error: incomplete escape /u at position 3
大概意思就是去掉前面的反寫杠之后剩下的 /u 不能組成完整的字符。
到這里問題好像有點難以解決了,這時候我們會放棄嗎?
當然不會,到谷歌上搜一下,發(fā)現(xiàn)還真有人碰到過這個問題,解決方法也是十分的巧妙。
竟然還可以使用 json 庫的 loads 方法 ...
解決方法如下:
import jsons = '//u9500//u552e'print(json.loads(f'"{s}"'))
PS:python3 將字符串unicode轉(zhuǎn)換為中文
記錄一個經(jīng)常會遇到的問題:
得到的文本打印出來是“/uxxxx”的字符串格式,在python3中使用text.decode('unicode_escape')會報錯:‘str' object has no attribute 'decode'
正確的姿勢是:
text.encode('utf-8').decode("unicode_escape")
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持武林站長站。
新聞熱點
疑難解答