Change Character in Sublist

2020-05-10 08:21发布

I already know this is a really dumb question. I tried looking up my answer but I barely know what to ask. (sorry if the title is a little vague). But Here I go. I have a list of words. I'm wanting to get rid of the bad characters in that list.

List = ["I?", "Can", "!Not", "Do.", "It"]
BadChars = ["?", "!", "."]

for word in List:
    for char in word:
        if char in BadChars:
            char = ""

print(List)

Again, I know this is very simple, but I just can't figure it out. Forgive me.

EDIT: Btw, it's not giving me an error. It's just returning the List untouched.

标签: python list
3条回答
劳资没心,怎么记你
2楼-- · 2020-05-10 08:27

You could use the replace method, for each char for each word:

List = ["I?", "Can", "!Not", "Do.", "It"]
BadChars = ["?", "!", "."]

for i in range(len(List)):
  for char in BadChars:
    List[i] = List[i].replace(char, "")

print(List) # ==> ['I', 'Can', 'Not', 'Do', 'It']

A regex may be used as well:

import re

List = ["I?", "Can", "!Not", "Do.", "It"]
BadChars = ["?", "!", "."]
rgx = '[%s]'%(''.join(BadChars))

List = [re.sub(rgx, "", word) for word in List]

print(List) # ==> ['I', 'Can', 'Not', 'Do', 'It']
查看更多
做个烂人
3楼-- · 2020-05-10 08:30

You can use a generator expression that iterates over each character in a string and retains characters that are not in BadChars:

[''.join(c for c in s if c not in BadChars) for s in List]

This returns:

['I', 'Can', 'Not', 'Do', 'It']
查看更多
Viruses.
4楼-- · 2020-05-10 08:36
List = ["I?", "Can", "!Not", "Do.", "It"]
l=[]
BadChars = ["?", "!", "."]
for i in List:
    for j in BadChars:
        if j in i:
            i=i.strip(j)
    l.append(i)


print(l)

Just use strip method to remove BadChars from List

查看更多
登录 后发表回答