[英]python convert unicode code value to string, without '\u'
在下面的代碼中,
text = "\u54c8\u54c8\u54c8\u54c8"
有沒有辦法將上面的 unicode 代碼轉換為僅保留值,並從中刪除“\\u”。\u003c/b> 所以"\哈"
變成了"54c8"
。
在 javascript 中,我可以執行text.charCodeAt(n).toString(16)
,但我無法在 python 中找出等效的解決方案。
我嘗試使用正則表達式來匹配它,
pattern = re.compile('[\u0000-\uFFFF]')
matches = pattern.finditer(text)
for match in matches:
print(match)
但它所做的只是打印出 unicode 值代表的字符。
您可以使用常規列表中理解到4個字符映射在以上text
,並使用ord
得到ord
碼點的伊納勒(整數),然后hex()
將其轉換為十六進制。 [2:]
切片需要擺脫 Python 否則會添加的0x
。
>>> text = "\u54c8\u54c8\u54c8\u54c8"
>>> text
'哈哈哈哈'
>>> [hex(ord(c))[2:] for c in text]
['54c8', '54c8', '54c8', '54c8']
>>>
如果您需要單個字符串,則可以使用例如"".join()
。
(另一種編寫理解式的方法是使用 f 字符串和x
十六進制格式:
>>> [f'{ord(c):x}' for c in text]
['54c8', '54c8', '54c8', '54c8']
)
如果您實際上有一個字符串\哈\哈\哈\哈
,即“反斜杠,u,五,四,c,八”重復了 4 次,您需要首先解碼反斜杠轉義序列以獲得 4 碼點細繩:
>>> text = r"\u54c8\u54c8\u54c8\u54c8"
>>> codecs.decode(text, "unicode_escape")
'哈哈哈哈'
您可以這樣做:您可以忽略非 ASCII 字符並編碼為 ASCII,或者您可以編碼為 UTF-8
text = "\u54c8\u54c8\u54c8\u54c8"
utf8string = text.encode("utf-8")
asciistring1 = text.encode("ascii", 'ignore')
asciistring2 = text.encode("ascii", 'replace')
可以參考https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s18.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.