Reputation: 209
I have a list of strings and need certain punctuation stripped off the end of each string within the list. The list is like:
list = ['Twas', 'brillig,', 'and', 'the', 'slithy', 'toves', 'Did', 'gyre',
'and', 'gimble', 'in', 'the', 'wabe:'] #the list is a lot longer
I need to strip off all punctuation that includes '"-,.:;!?
only from the end of each string and make all words lower case.
Io I need 'Twas'
to become 'twas'
and I need 'wabe:'
to become 'wabe'
, etc... other words in the list that i did not include here contain the other punctuation at the end.
I tried using .rstrip()
and .lower()
case but I did not know how to use a for or while loop to go through each string in the list and do this. If there is another way that does not need to use .rstrip
or .lower
I am open to them.
I am a beginner with using python so the very basic answer would help me and if you could explain exactly what you do, it would be greatly appreciated.
Upvotes: 1
Views: 3164
Reputation: 35269
>>> [el.lower().rstrip('\'\"-,.:;!?') for el in list]
['twas', 'brillig', 'and', 'the', 'slithy', 'toves', 'did', 'gyre', 'and', 'gimble', 'in', 'the', 'wabe']
This is a list comprehension, which is a one line way of writing a for loop which produces a list. It iterates through the list item by item, setting each element to lowercase, and then stripping trailing characters '"-,.:;!?
Upvotes: 8