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

前端 未结 2 378
生来不讨喜
生来不讨喜 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条回答
  • 2020-12-04 11:05

    I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

    We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

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

    However try to always use the in operator for string comparison as detailed in this post

    faster-operation-re-match-or-str

    Also detailed in the one of the best books to start learning python with

    idiomatic-python

    0 讨论(0)
  • 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']
    
    0 讨论(0)
提交回复
热议问题