Python3、Unicode、UTF-8、編碼


text = u'你好,今天天氣不錯'
text
print(text)

text = '\u4f60\u597d\uff0c\u4eca\u5929\u5929\u6c14\u4e0d\u9519'
text
print(text)

text = u'\u4f60\u597d\uff0c\u4eca\u5929\u5929\u6c14\u4e0d\u9519'
text
print(text)

text = '\\u4f60\\u597d\\uff0c\\u4eca\\u5929\\u5929\\u6c14\\u4e0d\\u9519'
text
print(text)
text = text.encode('utf-8').decode('unicode_escape')
text
print(text)

text = '\\u4f60\\u597d\\uff0c今天天氣不錯'
text
print(text)
import re
text = re.sub(r'(\\u[0-9a-fA-F]{4})', lambda matched: matched.group(1).encode('utf-8').decode('unicode_escape'), text)
text
print(text)

以上為運行的代碼,運行的結果如下:

>>> text = u'你好,今天天氣不錯'
>>> text
'你好,今天天氣不錯'
>>> print(text)
你好,今天天氣不錯

>>> text = '\u4f60\u597d\uff0c\u4eca\u5929\u5929\u6c14\u4e0d\u9519'
>>> text
'你好,今天天氣不錯'
>>> print(text)
你好,今天天氣不錯

>>> text = u'\u4f60\u597d\uff0c\u4eca\u5929\u5929\u6c14\u4e0d\u9519'
>>> text
'你好,今天天氣不錯'
>>> print(text)
你好,今天天氣不錯

>>> text = '\\u4f60\\u597d\\uff0c\\u4eca\\u5929\\u5929\\u6c14\\u4e0d\\u9519'
>>> text
'\\u4f60\\u597d\\uff0c\\u4eca\\u5929\\u5929\\u6c14\\u4e0d\\u9519'
>>> print(text)
\u4f60\u597d\uff0c\u4eca\u5929\u5929\u6c14\u4e0d\u9519
>>> text = text.encode('utf-8').decode('unicode_escape')
>>> text
'你好,今天天氣不錯'
>>> print(text)
你好,今天天氣不錯

>>> text = '\\u4f60\\u597d\\uff0c今天天氣不錯'
>>> text
'\\u4f60\\u597d\\uff0c今天天氣不錯'
>>> print(text)
\u4f60\u597d\uff0c今天天氣不錯
>>> import re
>>> text = re.sub(r'(\\u[0-9a-fA-F]{4})', lambda matched: matched.group(1).encode('utf-8').decode('unicode_escape'), text)
>>> text
'你好,今天天氣不錯'
>>> print(text)
你好,今天天氣不錯

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM