1
title = 'Example#@@@+||'

blacklisted_chars = ['#','|','@','+']

for i in blacklisted_chars:
    convert = title.replace(i, '')
    
print(convert)

# Example#@@@||

I want to remove all blacklisted characters in a list and replace them with '', however when the code is run only the final 'blacklisted_char' is replaced within the print statement

I am wondering how I would make it that all characters are replaced and only 'Example' is printed

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • In the loop, you are saving the result as `convert`. Each loop, you are _replacing_ the value of `convert`. – gen_Eric Oct 16 '20 at 17:22
  • Does this answer your question? [Best way to replace multiple characters in a string?](https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string) – ggorlen Oct 16 '20 at 17:56

2 Answers2

3

Try this :

title = 'Example#@@@+||'

blacklisted_chars = ['#','|','@','+']

for i in blacklisted_chars:
    title = title.replace(i, '')
    
print(title)

Explanation: Since you were storing the result of title.replace in the convert variable, every iteration it was being overwritten. What you need is to apply replace to the result of the previous iteration, which can be the variable with the original string or another variable containing a copy of it if you want to keep the original value unchanged.

P.S.: strings are iterables so you can also achieve the same results with something like this:

blacklisted_chars = '#|@+'
Hemerson Tacon
  • 2,419
  • 1
  • 16
  • 28
3

Strings are immutable in python. You assign a new string with

convert = title.replace(i, '')

title remains unchanged after this statement. convert is an entirely new string that is missing i.

On the next iteration, you replace a different value of i, but still from the original title. So in the end it looks like you only ran

convert = title.replace('+', '')

You have two very similar options, depending on whether you want to keep the original title around or not.

If you do, make another reference to it, and keep updating that reference with the results, so that each successive iteration builds on the result of the previous removal:

convert = title
for i in blacklisted_chars:
    convert = convert.replace(i, '')
    
print(convert)

If you don't care to retain the original title, use that name directly:

for i in blacklisted_chars:
    title = title.replace(i, '')
    
print(title)

You can achieve a similar result without an explicit loop using re.sub:

convert = re.sub('[#|@+]', '', title)
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264