首页 > 解决方案 > 删除python中分隔符之间的子字符串

问题描述

有没有一种有效的方法来删除python中两个分隔符之间的子字符串?例如从

"This $\textbf{word}$ must be deleted"

获得

"This must be deleted"

如果可能的话,我宁愿不使用正则表达式包。


此外,如果分隔符不相等怎么办,例如从

"This {word} must be deleted"

获得

"This must be deleted"

标签: pythonstringdelimiter

解决方案


如果您不想使用正则表达式,您可以执行以下操作:

s = "This $\textbf{word}$ must be deleted and this $here$ too"
d = '$'

''.join(s.split(d)[::2])
# 'This  must be deleted and this  too'

这会在分隔符上拆分,并且只保留所有其他标记。如果你想摆脱双空格,你可以这样做:

' '.join(x.strip() for x in s.split(d)[::2])
# 'This must be deleted and this too'

推荐阅读