替换Python中特定出现的字符串
如果我有替换Python中特定出现的字符串,python,string,substitution,Python,String,Substitution,如果我有 examplestring='hello abcde hello xyz hello goodbye'. 我想用“bye”替换第二次出现的“hello”,而不替换所有出现的“hello” 我该怎么做?你可以试试这个 re.sub(r'^(.*?hello.*?)hello', r'\1bye', s) 或 你可以试试这个 re.sub(r'^(.*?hello.*?)hello', r'\1bye', s) 或 您可以拆分然后加入: 您可以拆分然后加入: In [1]: s =
examplestring='hello abcde hello xyz hello goodbye'.
我想用“bye”替换第二次出现的“hello”,而不替换所有出现的“hello”
我该怎么做?你可以试试这个
re.sub(r'^(.*?hello.*?)hello', r'\1bye', s)
或
你可以试试这个
re.sub(r'^(.*?hello.*?)hello', r'\1bye', s)
或
您可以拆分然后加入:
您可以拆分然后加入:
In [1]: s = 'hello abcde hello xyz hello goodbye'
In [2]: words = s.split('hello')
In [3]: 'hello'.join(words[:2]) + 'bye' + 'hello'.join(words[2:])
Out[3]: 'hello abcde bye xyz hello goodbye'