Reputation: 117
My question is: how do I delete all the lowercase words from a string that is an element in a list? For example, if I have this list: s = ["Johnny and Annie.", "She and I."]
what do I have to write to make python return newlist = ["Johnny Annie", "She I"]
I've tried this, but it sadly doesn't work:
def test(something):
newlist = re.split("[.]", something)
newlist = newlist.translate(None, string.ascii_lowercase)
for e in newlist:
e = e.translate(None, string.ascii_lowercase)
Upvotes: 0
Views: 3217
Reputation: 2472
Iterate over the elements of the list and eliminate the words in lowercase.
s = s = ["Johnny and Annie.", "She and I."]
for i in s:
no_lowercase = ' '.join([word for word in i.split(' ') if not word.islower()])
print(no_lowercase)
Upvotes: 2
Reputation: 180441
use filter
with str.title
if you just want the words starting with uppercase letters:
from string import punctuation
s = ["Johnny and Annie.", "She and I."]
print([" ".join(filter(str.istitle,x.translate(None,punctuation).split(" "))) for x in s])
['Johnny Annie', 'She I']
Or use a lambda not x.isupper to remove all lowercase words:
[" ".join(filter(lambda x: not x.isupper(),x.translate(None,punctuation).split(" "))) for x in s]
Upvotes: 0
Reputation: 117886
>>> s = ["Johnny and Annie.", "She and I."]
You can check if the word is lowercase using islower()
and using split
to iterate word by word.
>>> [' '.join(word for word in i.split() if not word.islower()) for i in s]
['Johnny Annie.', 'She I.']
To remove punctuation as well
>>> import string
>>> [' '.join(word.strip(string.punctuation) for word in i.split() if not word.islower()) for i in s]
['Johnny Annie', 'She I']
Upvotes: 0
Reputation: 599630
Translate is not the right tool here. You can do it with a loop:
newlist = []
for elem in s:
newlist.append(' '.join(x for x in elem.split(' ') if x.lower() == x))
Upvotes: 0