1. 程式人生 > >Python2 處理 Unicode 字符串的規則

Python2 處理 Unicode 字符串的規則

unicode python2 round () -c 應該 nbsp mic fff

在 Python2 中處理 Unicode 字符串,需遵循如下規則:

1. 程序中的字符串要加前綴 u

2. 不要用 str(),而應該用 unicode() 作為字符串轉換函數。不要使用 chr(),而應該使用 unichr()

3. 不要使用 string 模塊

4. 如非必要,不要使用 encode 和 decode 編解碼 unicode 字符串。只有當要將 unicode 字符串寫入文件,數據庫,或者網絡時,要先將其 encode 為 byte stream,然後再寫入,同樣的,從文件,數據庫,或者網絡讀取的 byte stream 要先 decode 為 unicode 字符串,然後才能使用。

例如:

if __name__ == __main__:

    #str_out = u‘Hello world!‘
    str_out = u寧靜致遠
    print >>> str_out = %s % str_out  # for test

    byte_encode = str_out.encode(utf-8)

    # write the encoded bytes stream into file
    fho = open(use_unicode_encode_decode_3.log, 
w) fho.write(byte_encode) fho.close() # read the encoded bytes stream from file, and then decode it fhi = open(use_unicode_encode_decode_3.log, r) byte_in = fhi.read() fhi.close() str_in = byte_in.decode(utf-8) print <<< str_in = %s % str_in #
for test


完。

Python2 處理 Unicode 字符串的規則