redd 發表於 2017-3-8 02:21:43

Unicode

### input ###
print type("中文")
print type("中文".decode("utf-8"))
print type(u"中文")### output ###
<type 'str'>
<type 'unicode'>
<type 'unicode'>

註:python2

redd 發表於 2017-3-8 02:28:07

print "中文" # encoded in utf-8
print "中文".decode("utf-8").encode("big5") # encoded in big5
當你想要從 UTF-8 編碼狀態轉換成 Big5 編碼狀態時,你必需要將編碼狀態的字串先解碼成 Unicode 後,再重新編碼成 Big5 的編碼狀態才能成功。

註:python2

redd 發表於 2017-3-8 02:30:57

### input ###
print len("中文")
print len("中文".decode("utf-8"))
print len(u"中文")
### output ###
6
2
2

記得一定要以 Unicode 去計算字數才會得到正確的結果。

註:python2

redd 發表於 2017-3-8 02:36:48

python3
### input ###
print(type("中文"))
print(type("中文".encode("utf-8")))
print(type(u"中文"))
print(len("中文"))
### output ###
<class 'str'>
<class 'bytes'>
<class 'str'>
2

redd 發表於 2017-3-8 02:41:06

python3
### input ###
with open("filename.txt",'w',encoding='utf-8') as outfile:
    outfile.write("anything you want to write")
    ...

with open("filename.txt",'r',encoding='utf-8') as infile:
    text = infile.read()
print(type(text))
### output ###
<class 'str'>

注意: python2 的 I/O 物件並沒有支持 encoding 這個變數。

admin 發表於 2021-5-1 17:01:22

在第一行或第二行:
# coding=utf-8

# -*- coding: UTF-8 -*-
頁: [1]
查看完整版本: Unicode