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

时间:2021-11-06 13:05:58

I want to classify a list of string in Python depending on whether they are upper case, lower case, or mixed case

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

How can I do this?

我怎样才能做到这一点?

1 个解决方案

#1


113  

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

字符串上有许多“is methods”。 islower()和isupper()应该满足您的需求:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

以下是如何使用这些方法对字符串列表进行分类的示例:

>>> 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']

#1


113  

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

字符串上有许多“is methods”。 islower()和isupper()应该满足您的需求:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

以下是如何使用这些方法对字符串列表进行分类的示例:

>>> 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']