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.

Dan
  • 527
  • 4
  • 16
  • Possible duplicate of [How to replace all occurrences of a string in JavaScript?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Antimony Sep 22 '17 at 17:42
  • He meant python though. – oreofeolurin Sep 22 '17 at 17:49
  • 1
    Possible duplicate of [Replace nth occurrence of substring in string](https://stackoverflow.com/questions/35091557/replace-nth-occurrence-of-substring-in-string) – adder Sep 22 '17 at 17:49

3 Answers3

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'
wim
  • 338,267
  • 99
  • 616
  • 750
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"
oreofeolurin
  • 636
  • 3
  • 16
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)]))
Ajax1234
  • 69,937
  • 8
  • 61
  • 102