Reputation: 5425
I'm new in python and I'm having some issues doing a simple thing.
I've an array (or list as it's said in python) like this:
list = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
As you see each element of this array contains some words. These words is both lowercase and uppercase.
How I can delete from this array each lowercase words?
For example I'd like to have as result this list:
list = [ 'NICE' , 'FLOWER' , 'GOOD' , 'YELLOW']
Upvotes: 3
Views: 4805
Reputation: 4528
Here's a way to do it with the re
(regular expression) module:
list = map(lambda l: re.sub(r'\b\w*[a-z]+\w*\b','',l).strip(), list)
Upvotes: 1
Reputation: 3107
string.translate()
will quickly delete specified characters:
>>> import string
>>> mylist=['NICE dog', 'blue FLOWER', 'GOOD cat', 'YELLOW caw']
>>> print [s.translate(None, string.ascii_lowercase) for s in mylist]
['NICE', 'FLOWER', 'GOOD', 'YELLOW']
Upvotes: 2
Reputation: 212895
l = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
output = [' '.join(w for w in a.split() if w.isupper()) for a in l]
# or:
output = [' '.join(filter(str.isupper, a.split())) for a in l]
returns:
['NICE', 'FLOWER', 'GOOD', 'YELLOW']
(Don't use list
as variable name.)
Upvotes: 9
Reputation: 11395
lst = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
for i in range(len(lst)):
tmp = ""
for j in range(len(lst[i])):
if ord(lst[i][j]) <= ord('Z'):
tmp = tmp + lst[i][j]
lst[i] = tmp.strip()
print(lst) #['NICE', 'FLOWER', 'GOOD', 'YELLOW']
Upvotes: 0
Reputation: 22847
list = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
print [word for pair in list for word in pair.split() if not word.islower()]
Upvotes: 0
Reputation: 500407
The following will do it:
def remove_lower(s):
return ' '.join(w for w in s.split(' ') if not w.islower())
l = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
l = map(remove_lower, l)
Upvotes: 3