How to extract all UPPER from a string? Python

O.rka picture O.rka · Apr 8, 2013 · Viewed 24.3k times · Source
#input
my_string = 'abcdefgABCDEFGHIJKLMNOP'

how would one extract all the UPPER from a string?

#output
my_upper = 'ABCDEFGHIJKLMNOP'

Answer

piokuc picture piokuc · Apr 8, 2013

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'