我想根据它们是大写,小写还是混合大小写对Python中的字符串列表进行分类
我怎样才能做到这一点?
Answers:
字符串上有许多“ 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']
我想为此大声疾呼使用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
运算符进行字符串比较,如本文中所述
在开始学习python的最佳书籍之一中也有详细介绍