How to extract all UPPER from a string? Python How to extract all UPPER from a string? Python python python

How to extract all UPPER from a string? Python


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'


import strings = 'abcdefgABCDEFGHIJKLMNOP's.translate(None,string.ascii_lowercase)

string.translate(s, table[, deletechars]) function will delete all characters from the string that are in deletechars, a list of characters. Then, the string will be translated using table (we are not using it in this case).

To remove only the lower case letters, you need to pass string.ascii_lowercase as the list of letters to be deleted.

The table is None because when the table is None, only the character deletion step will be performed.


Higher order functions to the rescue!

filter(str.isupper, "abcdefgABCDEFGHIJKLMNOP")

EDIT: In case you don't know what filter does: filter takes a function and an iterable, and then applies the function to every element in the iterable. It keeps all of the values that return true and throws out all of the rest. Therefore, this will return "ABCDEFGHIJKLMNOP".