【发布时间】:2012-01-03 14:29:28
【问题描述】:
我想在 Python 中根据它们是大写、小写还是混合大小写来对字符串列表进行分类
我该怎么做?
【问题讨论】:
-
考虑 (1) 不是字母的字符和 (2) 根本没有大小写的字母的可能性。
我想在 Python 中根据它们是大写、小写还是混合大小写来对字符串列表进行分类
我该怎么做?
【问题讨论】:
字符串上有许多“is 方法”。 islower() 和 isupper() 应该可以满足您的需求:
>>> 'hello'.islower()
True
>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
以下是如何使用这些方法对字符串列表进行分类的示例:
>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']
【讨论】:
istitle() 只会评估字符串是否是标题大小写,不是是否是混合大小写。对于 'The quick Brown Fox' 这样的字符串,它将返回 false,因为这不是标题大小写(但显然是混合大小写)。
我想为此使用re 模块大喊大叫。特别是在区分大小写的情况下。
我们在编译正则表达式时使用选项re.IGNORECASE,以便在具有大量数据的生产环境中使用。
>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
但是请尝试始终使用in 运算符进行字符串比较,如本文所述
faster-operation-re-match-or-str
在开始学习 python 的最佳书籍之一中也有详细介绍
【讨论】: