【发布时间】:2020-06-08 19:49:28
【问题描述】:
如何替换每个单词中第一次出现的字符?
假设我有这个字符串:
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 substring when it occurs once, but not when twice in a row in 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('@@', '@') 将“@”从它再次出现的地方删除。
但是,我想知道:有没有办法一次性完成这个替换?
【问题讨论】:
-
您需要严格的正则表达式答案吗?
-
@SayandipDutta 原则上是的,但我也很想看看没有正则表达式的其他方法:)
-
只是为了确定,是否有类似
@Hello@There的字符串,而@不会是连续的? -
@JvdV 不,不会有这种情况。