简体   繁体   中英

Removing last character from each element in Python list

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.

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]

Eg:

>>> words = ['Duration$', 'Noun$', 'Adjective$']
>>> words = [word.rstrip("$") for word in words]
>>> words
['Duration', 'Noun', 'Adjective']
>>> [word+"$" for word in words]
['Duration$', 'Noun$', 'Adjective$']

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]
words = [ x[:-1] for x in words ]

将从每个项目中删除最后一个字符

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM