我想在 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']
关于python - 在 Python 中检查字符串是大写、小写还是混合大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8222855/