-1

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.

  • Possible duplicate of [Removing character in list of strings](https://stackoverflow.com/questions/8282553/removing-character-in-list-of-strings) – j-i-l Mar 16 '19 at 00:36
  • @davedwards I appreciate your comment. I already looked at this post about 20 minutes ago and it didn't help me. –  Mar 16 '19 at 00:36
  • 1
    you're almost there! Problem is that you set the variable `char` to `''` if it is in the `BadChars` list and leave the `word` unchanged. What you really want is setting the char in `word` to `''` if it is in `BadChars`, this can be done using the [`replace`](https://www.pythoncentral.io/pythons-string-replace-method-replacing-python-strings/) method, like `word.replace("?", "")` – j-i-l Mar 16 '19 at 00:40

3 Answers3

1

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']
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

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']
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0
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