Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
71 views
in Technique[技术] by (71.8m points)

python - 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

question from:https://stackoverflow.com/questions/65829037/how-do-i-remove-words-from-a-list-from-a-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...