1

This may seem odd, but I am trying to remove a part of an item contained in a list. Basically, I am trying to remove a specific character from multiple list elements. For example

list = ['c1','c2','c3','d1','s1']
list.remove('c')

I know that doing that wouldn't work, but is there any way to remove the "c"s in the list, and only the "c"s in Python 3?

3 Answers3

4
lst = [s.replace('c','') for s in lst]
# ['1','2','3','d1','s1']

List comprehensions are your friend. Also note the "list" is a keyword in Python, so I highly recommend you do not use it as a variable name.

James
  • 2,843
  • 1
  • 14
  • 24
2

Use list comprehensions,

list = ['c1','c2','c3','d1','s1']

list_ = [ x for x in list if "c" not in x ]  # removes elements which has "c"
print list_  # ['d1', 's1']
Marlon Abeykoon
  • 11,927
  • 4
  • 54
  • 75
  • 1
    Ah. Didn't think of this interpretation of the question, this could very well be what the asker is looking for. +1 – James Aug 01 '16 at 17:29
0
list1 = ['c1','c2','c3','d1','d2']

list2 = []

for i in range (len(list1)):
    if 'c' not in list1[i]:
        list2.append(list1[i])

print (list2) #['d1', 'd2']

and also this link may helpful

Link one

Community
  • 1
  • 1
caldera.sac
  • 4,918
  • 7
  • 37
  • 69