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

前端 未结 2 382
生来不讨喜
生来不讨喜 2020-12-04 10:23

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

How can I do this?

2条回答
  •  旧时难觅i
    2020-12-04 11:22

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

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

提交回复
热议问题