Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 755
O.rka Avatar asked Apr 08 '13 18:04

O.rka


People also ask

How do you find the uppercase of a string in Python?

Python Isupper() To check if a string is in uppercase, we can use the isupper() method. isupper() checks whether every case-based character in a string is in uppercase, and returns a True or False value depending on the outcome.

How do you convert a string to all upper cases in Python?

The upper() method converts all lowercase characters in a string into uppercase characters and returns it.

How do you print uppercase from a list in Python?

Uppercase. To turn a string to uppercase in Python, use the built-in upper() method of a string. To turn a list of strings to uppercase, loop through the list and convert each string to upper case.


2 Answers

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'
like image 118
piokuc Avatar answered Sep 17 '22 18:09

piokuc


import string
s = '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.

like image 45
herinkc Avatar answered Sep 20 '22 18:09

herinkc