Python2 和 3 中如何將(Unicode)字串轉換為小寫
Jinku Hu
2023年10月10日
Python
Python String
Python 3 轉換字串為小寫
從 Python 3.0 開始字串 str 型別預設就包含了 Unicode 字元,也就是說所有的字串比如 "unicode example", 'unicode example 2'都是按照 Unicode 來儲存的。
因此,在 Python 3 中你可以用 str.lower() 方法將任何的字串,不論其中是否包含 Unicode 字元,轉換為小寫型別。
exampleString = "CaseString"
exampleString.lower()
# Out: 'casestring'
exampleString = "СтрокаСлучая"
exampleString.lower()
# Out: 'строкаслучая'
Python 2.7 轉換字串為小寫
Python 2.7 中的字串 str 型別不是按照 Unicode 編碼來儲存的,Unicode 字串是 Python 2.7 中的 unicode 型別的例項。我們將字串轉換為小寫時,我們必須區分字串是 ASCII 字串還是 unicode 字串。
ASCII 型別
它與 Python 3 中使用的方法相同。str.lower() 將字串 str 轉換為小寫。
exampleString = "CaseStringExample"
exampleString.lower()
# Out: 'casestringexample'
unicode 型別
如果字串中的字元是 unicode 型別且未用 unicode 型別來明確表示,則 str.lower() 方法根本不會將字串轉換為小寫。
# python 2.x
exampleString = "СтрокаСлучая"
print exampleString.lower()
#Out: СтрокаСлучая
exampleString.lower() == exampleString
#Out: True
使用 Unicode 而不是 str
我們需要定義包含 Unicode 字元的字串為 unicode 型別,也就是在字串的前面需要加上 u。
exampleUnicodeString = u"СтрокаСлучая"
exampleUnicode
# u'\u0421\u0442\u0440\u043e\u043a\u0430\u0421\u043b\u0443\u0447\u0430\u044f'
exampleUnicodeString.lower()
# u'\u0441\u0442\u0440\u043e\u043a\u0430\u0441\u043b\u0443\u0447\u0430\u044f'
print exampleUnicodeString.lower()
# Out: строкаслучая
可以看到字串的第一個字元從\u0421 轉換為\u0441。
將 str 轉換為 unicode
如果給定的字串是 str 形式,我們需要先將其轉換為 unicode,然後再進行小寫轉換。
exampleString = "СтрокаСлучая"
print exampleString.decode("utf-8").lower()
# Out: строкаслучая
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Jinku Hu
