Replace bad characters in python

Viewed 72

Please help, the print (line) will return Hello$ Python#. It should be "Hello Python"

line = "Hello$ Python#"

for char in line:
    if char in "$#":
        line.replace(char,'')

print (line)

1 Answers

The problem with what your doing is: You are altering the string line in a loop using the replace method without assigning it to anything. You should create a new variable to store the new string.

Try this:

line = "Hello$ Python#"
return_line = ""
for char in line:
  if char not in "$#":
    return_line += char

print(return_line)
Related