检查字符串在Python中是全大写、小写还是混合大小写

111 投票
2 回答
173561 浏览
提问于 2025-04-17 06:49

我想在Python中对一串字符串进行分类,看看它们是全大写、全小写,还是混合大小写。

我该怎么做呢?

2 个回答

2

我想推荐一下使用 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的书中也有详细介绍。

idiomatic-python

197

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

撰写回答