繁体   English   中英

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

[英]Check if string is upper, lower, or mixed case in Python

我想在Python中对字符串列表进行分类,具体取决于它们是大写,小写还是混合大小写

我怎样才能做到这一点?

字符串上有许多“is methods”。 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运算符进行字符串比较,如本文所述

更快的操作,重新匹配或-STR

还详细介绍了开始学习python的最佳书籍之一

地道的Python

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM