【发布时间】:2021-08-26 04:57:19
【问题描述】:
我有以下字符串:
somestring = "Zero function argument 1 since code 345 and from code 8476 then it goes on"
我想删除 since code 345 和 from code 8476(这些数字可能会有所不同),但我想在字符串中保留 argument 1 中的 1。
我正在做以下事情:
import re
somestring = "Zero function argument 1 since code 345 and from code 8476 then it goes on"
somestring = somestring.replace("since code", "").replace("from code", "")
stringlist = somestring.split(" ")
pattern = '[0-9]'
print([re.sub(pattern, "", i) for i in stringlist])
但输出会从字符串中的argument 1 中删除1。输出如下所示:
['Zero', 'function', 'argument', '', '', '', 'and', '', '', 'then', 'it', 'goes', 'on']
但我想要的理想输出是Zero function argument 1 and then it goes on,即删除since code和from code之后的任何数字,删除“since code”和“from code”,并且在字符串或列表中没有'' .
如何做到这一点?
【问题讨论】:
标签: python python-3.x regex string