Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
替换Python中特定出现的字符串_Python_String_Substitution - Fatal编程技术网

替换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'