1

Suppose I have

examplestring='hello abcde hello xyz hello goodbye'.

I want to substitute the second occurrence of 'hello' with 'bye' without substituting all occurrences of 'hello'.

How do I do this?

2 Answers 2

2

You could split and then join:

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'
Sign up to request clarification or add additional context in comments.

Comments

2

You may try this,

re.sub(r'^(.*?hello.*?)hello', r'\1bye', s)

or

re.sub(r'^(.*?\bhello\b.*?)\bhello\b', r'\1bye', s)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.