检查Python中字符串是大写,小写还是混合大小写


92

我想根据它们是大写,小写还是混合大小写对Python中的字符串列表进行分类

我怎样才能做到这一点?


1
考虑以下可能性:(1)不是字母的字符和(2)完全没有大小写的字母。
约翰·马钦

Answers:


173

字符串上有许多“ 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']

你好 感谢您的简短回答。但是,如何对大写单词进行分类呢?例如:“混合词”。似乎第三个示例适合所有混合单词的组合,例如:“ mIxEd WoRD”。– Swadhikar
2016年

10
'hello'.istitle()
斯蒂芬·斯蒂芬,

1

我想为此大声疾呼使用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运算符进行字符串比较,如本文中所述

更快的操作重新匹配或str

在开始学习python的最佳书籍之一中也有详细介绍

惯用的python

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.