在 Python 中將字串轉換為 Unicode
    
    Muhammad Maisam Abbas
    2023年1月30日
    
    Python
    Python Unicode string
    
 
本教程將討論在 Python 中將常規字串轉換為 Unicode 字串。
在 Python 2 中將字串轉換為 Unicode
在 Python 2 中,常規字串稱為位元組字串,我們可以使用內建的 unicode() 函式 將這些位元組字串轉換為 Unicode 字串。此程式碼片段向我們展示瞭如何在 Python 2 中將常規字串轉換為 Unicode 字串。
regular = "regular string"
unicode_string = unicode(regular, "utf-8")
print(type(regular))
print(type(unicode_string))
輸出:
<type 'str'>
<type 'unicode'>
我們使用 Python 2 中的 unicode() 函式將常規位元組字串轉換為 Unicode 字串。
在 Python 3 中將字串轉換為 Unicode 格式
在 Python 3 中,預設情況下字串是 Unicode 字串,我們無法將常規字串轉換為 Unicode 字串。因此,以下程式碼在 Python 2 和 Python 3 上給出了不同的結果。
regular = "regular string"
unicode_string = u"Unicode string"
print(type(regular))
print(type(unicode_string))
Python 2 輸出:
<type 'str'>
<type 'unicode'>
Python 3 輸出:
<class 'str'>
<class 'str'>
在上面的程式碼中,我們在 Python 2 和 Python 3 中都初始化了一個 Unicode 字串。在 Python 2 中,字串屬於 unicode 類,因為常規字串和 Unicode 字串之間存在區別,而在 Python 3 中,字串屬於類 str。畢竟,Unicode 字串與常規字串相同。
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn