如何在 Python 中小写字符串?

新手上路,请多包涵

有没有办法将字符串转换为小写?

 "Kilometers"  →  "kilometers"

原文由 Benjamin Didur 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 940
2 个回答

这样做的规范 Pythonic 方式是

>>> 'Kilometers'.lower()
'kilometers'

但是,如果目的是进行不区分大小写的匹配,则应使用大小写折叠:

 >>> 'Kilometers'.casefold()
'kilometers'

原因如下:

 >>> "Maße".casefold()
'masse'
>>> "Maße".lower()
'maße'
>>> "MASSE" == "Maße"
False
>>> "MASSE".lower() == "Maße".lower()
False
>>> "MASSE".casefold() == "Maße".casefold()
True

这是 Python 3 中的一个 str 方法,但在 Python 2 中,您需要查看 PyICU 或 py2casefold - 此处有几个答案解决了这个问题

统一码 Python 3

Python 3 将纯字符串文字作为 unicode 处理:

 >>> string = 'Километр'
>>> string
'Километр'
>>> string.lower()
'километр'

Python 2,纯字符串文字是字节

在 Python 2 中,下面粘贴到 shell 中的代码使用 utf-8 将文字编码为字节串。

并且 lower 没有映射字节会知道的任何更改,因此我们得到相同的字符串。

 >>> string = 'Километр'
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.lower()
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.lower()
Километр

在脚本中,Python 将反对非 ascii(从 Python 2.5 开始,并在 Python 2.4 中发出警告)字节出现在没有给出编码的字符串中,因为预期的编码会产生歧义。有关更多信息,请参阅 文档PEP 263 中的 Unicode 操作指南

使用 Unicode 文字,而不是 str 文字

所以我们需要一个 unicode 字符串来处理这个转换,使用 unicode 字符串文字很容易完成,它用 u 前缀消除歧义(并注意 u 适用于 Python 3):

 >>> unicode_literal = u'Километр'
>>> print(unicode_literal.lower())
километр

请注意,字节与 str 字节完全不同 - 转义字符是 '\u' 后跟 2 字节宽度,或这些的 16 位表示 unicode 信件:

 >>> unicode_literal
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> unicode_literal.lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'

现在,如果我们只有 str 的形式,我们需要将其转换为 unicode 。 Python 的 Unicode 类型是一种通用编码格式,相对于大多数其他编码具有许多 优点。 We can either use the unicode constructor or str.decode method with the codec to convert the str to unicode :

 >>> unicode_from_string = unicode(string, 'utf-8') # "encoding" unicode from string
>>> print(unicode_from_string.lower())
километр
>>> string_to_unicode = string.decode('utf-8')
>>> print(string_to_unicode.lower())
километр
>>> unicode_from_string == string_to_unicode == unicode_literal
True

这两种方法都转换为 unicode 类型 - 并且与 unicode_literal 相同。

最佳实践,使用 Unicode

建议您始终 使用 Unicode 中的文本

软件应该只在内部使用 Unicode 字符串,在输出时转换为特定的编码。

必要时可以编码回来

但是,要在类型 str 中恢复小写字母,再次将 python 字符串编码为 utf-8

 >>> print string
Километр
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.decode('utf-8')
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower().encode('utf-8')
'\xd0\xba\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.decode('utf-8').lower().encode('utf-8')
километр

所以在 Python 2 中,Unicode 可以编码成 Python 字符串,Python 字符串可以解码成 Unicode 类型。

原文由 Russia Must Remove Putin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题