簡體   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