删除python中分隔符之间的子字符串

问题描述 投票:1回答:2

是否有一种有效的方法来删除python中两个定界符之间的子字符串?例如从

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

获得

"This must be deleted"

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

python string delimiter
2个回答
1
投票

您可以做一些str.partition

>>> x = "This $\textbf{word}$ must be deleted"
>>> f, _, rest = x.partition('$')
>>> _, _, r = rest.partition('$')
>>> ' '.join([f.strip(), r.strip()])
'This must be deleted'

1
投票

如果您不想使用正则表达式,可以按照以下几行做一些事情:

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(delim)[::2])
# 'This must be deleted and this too'
© www.soinside.com 2019 - 2024. All rights reserved.