Samuel du Plessis
Samuel du Plessis

Reputation: 13

How do I remove words from a list from a string?

I want to be able to remove words I have stored in a list from a string. currently my code is as follows:

old_string = "BANK TRANSACTION NUM1204012 JOHN"
remove_list = ['BANK TRASACTION', 'PAYMENT TO', 'PAYMENT FROM', 'BANK FEE']
for x in range(len(remove_list)):
      new_string = old_string.replace(remove_list[x], "")

This method didn't change anything in the strings The old string will also be changing every time in a different for loop, I am trying to remove the unnecessary words from bank statements in order to have them presented neater. I want to be able to keep the number and the name, but remove the rest I would for example like: new_string = NUM1204012 JOHN I have also tried using regex

new_string = re.sub(remove_list[x], '', old_string)

but this method removed every instance of a character in remove_list

Upvotes: 1

Views: 212

Answers (2)

David Michael Gang
David Michael Gang

Reputation: 7299

Going with your implementation you need to do the following

old_string = "BANK TRANSACTION NUM1204012 JOHN"
remove_list = ['BANK TRANSACTION', 'PAYMENT TO', 'PAYMENT FROM', 'BANK FEE']
new_string = old_string
for to_remove in remove_list:
      new_string = new_string.replace(to_remove, "")

But this solution is not optimal. you have also a typo in remove_list

Upvotes: 0

arshovon
arshovon

Reputation: 13651

You are storing the updated sting in new_string. That is why the string is not changed. Replaced it with the old_string.

old_string = "BANK TRANSACTION NUM1204012 JOHN"
remove_list = ['BANK TRANSACTION', 'PAYMENT TO', 'PAYMENT FROM', 'BANK FEE']
for x in remove_list:
      old_string = old_string.replace(x, "")

print(old_string.strip())

Explanation

  • Replaced the old string content completely.
  • The last strip method is used to remove the spaces from the beginning and ending of the string.

Output

NUM1204012 JOHN

Upvotes: 1

Related Questions