4 回答
TA贡献1788条经验 获得超4个赞
使用额外的“反向”替换步骤:
s = "SELECT sdfdsf SELECT sdrrr SELECT 5445ff"
res = s.replace("SELECT", "@@@SELECT").replace("@@@SELECT", "SELECT", 1)
print(res)
输出:
SELECT sdfdsf @@@SELECT sdrrr @@@SELECT 5445ff
更复杂但确保目标单词边界的方法如下:
import re
def make_replacer():
rpl = ''
def inner(m):
nonlocal rpl
res = rpl + m.group()
rpl = '@@@'
return res
return inner
s = "SELECT sdfdsf SELECT sdrrr SELECT 5445ff"
res = re.sub(r'\bSELECT\b', make_replacer(), s)
print(res) # SELECT sdfdsf @@@SELECT sdrrr @@@SELECT 5445ff
TA贡献1876条经验 获得超6个赞
您可以使用方法partition和replace。工作代码如下所示:
string = "SELECT sdfdsf SELECT sdrrr SELECT 5445ff"
parts = string.partition("SELECT") # returns a tuple
results = parts[0] + parts[1] + parts[2].replace("SELECT", "@@@SELECT")
print(results)
所以你会得到:
选择 sdfdsf @@@SELECT sdrr @@@SELECT 5445ff
如果string = "Blabla is SELECT sdfdsf SELECT sdrrr SELECT 5445ff",您将得到:
Blabla 是 SELECT sdfdsf @@@SELECT sdrrr @@@SELECT 5445ff
TA贡献1784条经验 获得超8个赞
您可以itertools.count使用re.sub:
import re, itertools
c = itertools.count()
string = "SELECT sdfdsf SELECT sdrrr SELECT 5445ff"
r = re.sub(r"\bSELECT\b", lambda x:x.group() if not next(c) else f'@@@{x.group()}', string)
输出:
'SELECT sdfdsf @@@SELECT sdrrr @@@SELECT 5445ff'
但是,如果SELECT总是放在字符串的开头,您可以使用否定的lookbehind:
r = re.sub('(?<!^)SELECT', lambda x:f'@@@{x.group()}', string)
输出:
'SELECT sdfdsf @@@SELECT sdrrr @@@SELECT 5445ff'
TA贡献1850条经验 获得超11个赞
另一种方法:
import re
from itertools import chain, repeat
string = 'SELECT sdfdsf SELECT sdrrr SELECT 5445ff'
string = ''.join(x + s for x, s in zip(chain(['', 'S'], repeat('@@@S')), re.split(r'\bS(?=ELECT\b)', string)))
print(string)
输出:
SELECT sdfdsf @@@SELECT sdrrr @@@SELECT 5445ff
添加回答
举报