2

I know that the following is how to replace a string with another string i

line.replace(x, y)

But I only want to replace the second instance of x in the line. How do you do that? Thanks

EDIT I thought I would be able to ask this question without going into specifics but unfortunately none of the answers worked in my situation. I'm writing into a text file and I'm using the following piece of code to change the file.

with fileinput.FileInput("Player Stats.txt", inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(chosenTeam, teamName), end='')

But if chosenTeam occurs multiple times then all of them are replaced. How can I replace only the nth instance in this situation.

3

3 Answers 3

4

That's actually a little tricky. First use str.find to get an index beyond the first occurrence. Then slice and apply the replace (with count 1, so as to replace only one occurrence).

>>> x = 'na'
>>> y = 'banana'
>>> pos = y.find(x) + 1
>>> y[:pos] + y[pos:].replace(x, 'other', 1)
'banaother'
Sign up to request clarification or add additional context in comments.

Comments

2

Bonus, this is a method to replace "NTH" occurrence in a string

def nth_replace(str,search,repl,index):
    split = str.split(search,index+1)
    if len(split)<=index+1:
        return str
    return search.join(split[:-1])+repl+split[-1]

example:

nth_replace("Played a piano a a house", "a", "in", 1) # gives "Played a piano in a house"

Comments

1

You can try this:

import itertools
line = "hello, hi hello how are you hello"
x = "hello"
y = "something"
new_data = line.split(x)
new_data = ''.join(itertools.chain.from_iterable([(x, a) if i != 2 else (y, a) for i, a in enumerate(new_data)]))

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.