Using Replace Method in a For Loop

Viewed 117

Despite the code below, the string remains completely unchanged when it is printed out in the tkinter grid. I'd like for it to remove every character in disallowedCharacters. There must be something I'm not understanding about how strings can change. Note that itemSeries is passed to the following code from another function that grabs the text from the web using Selenium.

itemSeriesString = str(itemSeries)
disallowedCharacters = "()#1234567890"
for character in disallowedCharacters:
    seriesName = itemSeriesString.replace(character, "")

itemSeriesLabel = Label(frame, text="Series:", font='time 12 bold')
itemSeriesLabel.grid(column=2, row=4, sticky='w', padx=10)
itemPrintSeries = Label(frame, text=seriesName)
itemPrintSeries.grid(column=3, row=4, sticky='e')

I tried escaping the (, ), and # characters, but it didn't change anything.

1 Answers

Remember that .replace() never modifies the original string; it returns a new string with the result of the operation.

At every iteration of the for loop, you are:

  • taking the original, uncleaned itemSeriesString
  • filtering out all instances of one character from that original string
  • assigning the result of that filtering to seriesName.

You're never accumulating the results of the replacement operations, so most of the forbidden characters will remain.

You should use the same variable on the left and right hand side, so that you can accumulate the results of the replacement operations:

disallowedCharacters = "()#1234567890"
seriesName = itemSeriesString
for character in disallowedCharacters:
    seriesName = seriesName.replace(character, "")

Or, even better, just filter out those characters using filter():

seriesName = ''.join(filter(lambda x: x not in disallowedCharacters, itemSeriesString))
Related