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?

1
  • What's your expected output? Commented Aug 1, 2016 at 20:15

3 Answers 3

3
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.

Sign up to request clarification or add additional context in comments.

1 Comment

The variable list was an example. This was not meant to be functional Python code. But thank you so much!
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']

1 Comment

Ah. Didn't think of this interpretation of the question, this could very well be what the asker is looking for. +1
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.