Issue
What's an efficient way in Python (plain or using numpy) to remove all lowercase substring from a string s
?
s = "FOObarFOOObBAR"
remove_lower(s) => "FOOFOOBAR"
Solution
Python3.x answer:
You can make a string translation table. Once that translation table has been created, you can use it repeatedly:
>>> import string
>>> table = str.maketrans('', '', string.ascii_lowercase)
>>> s = 'FOObarFOOObBAR'
>>> s.translate(table)
'FOOFOOOBAR'
When used this way, the first argument values map to the second argument values (where present). If absent, it is assumed to be an identity mapping. The third argument is the collection of values to be removed.
Old python2.x answer for anyone who cares:
I'd use str.translate
. Only the delete step is performed if you pass None
for the translation table. In this case, I pass the ascii_lowercase
as the letters to be deleted.
>>> import string
>>> s = 'FOObarFOOObBAR'
>>> s.translate(None, string.ascii_lowercase)
'FOOFOOOBAR'
I doubt you'll find a faster way, but there's always timeit
to compare different options if someone is motivated :).
Answered By - mgilson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.