如何替换每个单词中第一次出现的字符?
说我有这个字符串:
hello @jon i am @@here or @@@there and want some@thing in '@here"
# ^ ^^ ^^^ ^ ^
Run Code Online (Sandbox Code Playgroud)
我想删除@每个单词的第一个,以便我最终得到一个像这样的最终字符串:
hello jon i am @here or @@there and want something in 'here
# ^ ^ ^^ ^ ^
Run Code Online (Sandbox Code Playgroud)
只是为了澄清,“@”字符在每个单词中总是一起出现,但可以在单词的开头或其他字符之间。
I managed to remove the "@" character if it occurs just once by using a variation of the regex I found in Delete substring when it occurs once, but not when twice in a row in python, which uses a negative lookahead and negative lookbehind:
@(?!@)(?<!@@)
Run Code Online (Sandbox Code Playgroud)
See the output:
>>> 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"
Run Code Online (Sandbox Code Playgroud)
So the next step is to replace the "@" when it occurs more than once. This is easy by doing s.replace('@@', '@') to remove the "@" from wherever it occurs again.
However, I wonder: is there a way to do this replacement in one shot?
Tim*_*sen 51
我会对以下模式进行正则表达式替换:
@(@*)
Run Code Online (Sandbox Code Playgroud)
然后用第一个捕获组替换,它是所有连续的 @ 符号,减去一个。
这应该捕获@出现在每个单词开头的每个单词,无论是在字符串的开头、中间还是结尾的单词。
inp = "hello @jon i am @@here or @@@there and want some@thing in '@here"
out = re.sub(r"@(@*)", '\\1', inp)
print(out)
Run Code Online (Sandbox Code Playgroud)
这打印:
hello jon i am @here or @@there and want something in 'here
Run Code Online (Sandbox Code Playgroud)
Guy*_*Guy 36
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"
Run Code Online (Sandbox Code Playgroud)
的 int 值1是可选count参数。
str.replace(old, new[, count])
返回字符串的副本,其中所有出现的子字符串old 都被new替换。如果给出了可选参数 计数,则仅替换第一个计数出现。
| 归档时间: |
|
| 查看次数: |
4037 次 |
| 最近记录: |