Reputation: 3102
I have a list find_words which is
[u'Duration$', u'Noun$', u'Adjective$']
I would like to remove all the '$' so it looks like
[u'Duration', u'Noun', u'Adjective']
How do I go about this? Also, how do I re-add the '$' as well.
Upvotes: 2
Views: 5614
Reputation: 27048
List comprehension is your friend.
You have a choice to remove just the last character word[:-1]
or a $ if it's present word.rstrip('$')
. This is going to be application defined
words = [u'Duration$', u'Noun$', u'Adjective$']
result = [word[:-1] for word in words]
Also to re-add it:
added_back = [word + '$' for word in result]
Upvotes: 3
Reputation: 4412
words = [ x[:-1] for x in words ]
will remove last character from each item
Upvotes: 3
Reputation: 88977
You can do this simply with a list comprehension and str.rstrip()
:
[word.rstrip("$") for word in words]
Or to add them:
[word+"$" for word in words]
E.g:
>>> words = ['Duration$', 'Noun$', 'Adjective$']
>>> words = [word.rstrip("$") for word in words]
>>> words
['Duration', 'Noun', 'Adjective']
>>> [word+"$" for word in words]
['Duration$', 'Noun$', 'Adjective$']
Upvotes: 6
Reputation: 11467
To remove the last character, regardless of what it is:
find_words = [i[:-1] for i in find_words]
But you should be using rstrip
if it's guaranteed to be a $
:
find_words = [i.rstrip("$") for i in words]
To add a $
:
find_words = [i + "$" for i in find_words]
Upvotes: 1