本文主要介绍Python中,使用正则表达式或生成器表达式来替换每个单词中出现第一个字符的方法,也可以是多个空格或其它分隔符分隔的字符串。

示例字符串

string =  "cjavapy @jon c cjavapy @@here python @@@there value path some@thing go '@here"

1、使用正则表达式替换

替换为第一个捕获组,该捕获组是所有连续的@符号,去掉一个。

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

string =  "cjavapy @jon c cjavapy @@here python @@@there value path some@thing go '@here"
out = re.sub(r"@(@*)", '\\1', string)
print(out)

输出:

"cjavapy jon c cjavapy @here python @@there value path something go 'here"

2、使用生成器表达式替换

result = ' '.join(s.replace('@', '', 1) for s in string.split(' '))

输出:

"cjavapy jon c cjavapy @here python @@there value path something go 'here"

推荐文档