如何替换每个单词中第一个出现的字符?


44

如何替换每个单词中第一个出现的字符?

说我有这个字符串:

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停止伤害'

只是为了确定,是否会有这样的字符串:@Hello@There在哪里@不连续?
JvdV

1
@JvdV不,不会有这种情况。
fedorqui'SO停止伤害'

Answers:


51

我将按照以下模式进行正则表达式替换:

@(@*)

然后只需替换为第一个捕获组,该捕获组是所有连续的@符号,减去一个。

这应该捕获@在每个单词的开头出现的所有单词,无论该单词出现在字符串的开头,中间还是结尾。

inp = "hello @jon i am @@here or @@@there and want some@thing in '@here"
out = re.sub(r"@(@*)", '\\1', inp)
print(out)

打印:

hello jon i am @here or @@there and want something in 'here

35

怎么样使用 replace('@', '', 1)在生成器表达式中?

string = 'hello @jon i am @@here or @@@there and want some@thing in "@here"'
result = ' '.join(s.replace('@', '', 1) for s in string.split(' '))

# output: hello jon i am @here or @@there and want something in "here"

的int值1是可选count参数。

str.replace(old, new[, count])

返回字符串的副本串中出现的所有旧的换成新的。如果给出了可选的参数 count,则仅替换第一个出现的计数


5
这是一个聪明的把戏!由于replace的第三个参数是replace(search, replace, max_matches),因此它仅替换每个单词上的第一个参数。
fedorqui'停止伤害'

1
@ fedorqui'SOstopharming'是的,它叫做count,我在文档中添加了说明。
盖伊

2
注意这种副作用:万一您有多个空格(''),它们将丢失并被单个''代替。
Marc Vanhoomissen

4

您可以这样使用re.sub

import re

s = "hello @jon i am @@here or @@@there and want some@thing in '@here"
s = re.sub('@(\w)', r'\1', s)
print(s)

这将导致:

"hello jon i am @here or @@there and want something in 'here"

这是概念证明:

>>> import re
>>> s = "hello @jon i am @@here or @@@there and want some@thing in '@here"
>>> re.sub('@(\w)', r'\1', s)
"hello jon i am @here or @@there and want something in 'here"
>>> 

2

在考虑某些情况下,如果只有最后一个字符@并且您不想删除它,或者您有特定的允许起始字符,该怎么办:

>>> ' '.join([s_.replace('@', '', 1) if s_[0] in ["'", "@"] else s_ for s_ in s.split()])
"hello jon i am @here or @@there and want some@thing in 'here"

或者,假设您只想替换@前n个字符

>>> ' '.join([s_.replace('@', '', 1) if s_.find('@') in range(2) else s_ for s_ in s.split()])
"hello jon i am @here or @@there and want some@thing in 'here"


1
# Python3 program to remove the @ from String


def ExceptAtTheRate(string):
    # Split the String based on the space
    arrOfStr = string.split()

    # String to store the resultant String
    res = ""

    # Traverse the words and
    # remove the first @ From every word.
    for a in arrOfStr:
        if(a[0]=='@'):
            res += a[1:len(a)] + " "
        else:
            res += a[0:len(a)] + " "

    return res


# Driver code
string = "hello @jon i am @@here or @@@there and want some@thing in '@here"

print(ExceptAtTheRate(string))

输出:

在此处输入图片说明


谢谢!请注意,@中的一些事情@“@here也应该被删除,按我的要求。
fedorqui'SO停止伤害'
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.