[英]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.此方法没有改变字符串中的任何内容旧字符串也将在每次不同的 for 循环中发生变化,我试图从银行对帐单中删除不必要的单词,以使它们呈现得更整洁。 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
我希望能够保留数字和名称,但删除 rest 我想例如: new_string = NUM1204012 JOHN 我也尝试过使用正则表达式
new_string = re.sub(remove_list[x], '', old_string)
but this method removed every instance of a character in remove_list但是此方法删除了 remove_list 中字符的每个实例
You are storing the updated sting in new_string
.您将更新的字符串存储在
new_string
中。 That is why the string is not changed.这就是字符串没有改变的原因。 Replaced it with the
old_string
.将其替换为
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解释
old string
content completely.old string
内容。strip
method is used to remove the spaces from the beginning and ending of the string.strip
方法用于删除字符串开头和结尾的空格。 Output Output
NUM1204012 JOHN
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
您在 remove_list 中也有错字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.