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
