如何替换每个单词中第一个出现的字符?
说我有这个字符串:
hello @jon i am @@here or @@@there and want some@thing in '@here"
# ^ ^^ ^^^ ^ ^
我想删除@
每个单词的第一个,以便最终得到一个像这样的最终字符串:
hello jon i am @here or @@there and want something in 'here
# ^ ^ ^^ ^ ^
只是为了澄清起见,“ @”字符始终在每个单词中同时出现,但可以出现在单词的开头或其他字符之间。
我设法通过使用在Delete子串中发现的正则表达式的变体(仅一次出现)来删除“ @”字符(一次出现),但是在python中连续两次出现时却没有,因此使用了负向超前和负向超前:
@(?!@)(?<!@@)
查看输出:
>>> s = "hello @jon i am @@here or @@@there and want some@thing in '@here"
>>> re.sub(r'@(?!@)(?<!@@)', '', s)
"hello jon i am @@here or @@@there and want something in 'here"
因此,下一步是替换出现多次的“ @”。通过s.replace('@@', '@')
从再次出现的地方删除“ @”,很容易。
但是,我想知道:有没有办法一次完成一次替换?
1
您是否需要严格的正则表达式答案?
—
Sayandip Dutta
@SayandipDutta原则上是的,但是我也很想知道其他没有正则表达式的方法:)
—
fedorqui'SO停止伤害'
只是为了确定,是否会有这样的字符串:
—
JvdV
@Hello@There
在哪里@
不连续?
@JvdV不,不会有这种情况。
—
fedorqui'SO停止伤害'