Search code examples
pythonstringextractuppercaselowercase

How to extract all UPPER from a string? Python


#input
my_string = 'abcdefgABCDEFGHIJKLMNOP'

how would one extract all the UPPER from a string?

#output
my_upper = 'ABCDEFGHIJKLMNOP'

Solution

  • Using list comprehension:

    >>> s = 'abcdefgABCDEFGHIJKLMNOP'
    >>> ''.join([c for c in s if c.isupper()])
    'ABCDEFGHIJKLMNOP'
    

    Using generator expression:

    >>> ''.join(c for c in s if c.isupper())
    'ABCDEFGHIJKLMNOP
    

    You can also do it using regular expressions:

    >>> re.sub('[^A-Z]', '', s)
    'ABCDEFGHIJKLMNOP'