I would like to find and replace a string in a file. I know how to do this, but I can only do it for all instances. Is there a way to do it for just the first instance of the string in the file?

import fileinput
for line in fileinput.FileInput("text.txt", inplace=1):
line=line.replace("hello","hello2")
print line

Use the interpreter !

>>> help(str.replace)
Help on method_descriptor:

replace(...)
    S.replace (old, new[, count]) -> string
    
    Return a copy of string S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.

Thanks a lot. I will try this.

Use some kind of a switch that you turn on after the first instance is found.

import fileinput
string_found = False
for line in fileinput.FileInput("text.txt", inplace=1):
    if (not string_found) and ("hello" in line):
        line=line.replace("hello","hello2")
        print line
        string_found = True

Thanks for your help. This works if you want to keep all the other lines in the file.

import fileinput
string_found = False
for line in fileinput.FileInput("text.txt", inplace=1):
    if (not string_found) and ("hello" in line):
        line=line.replace("hello","hello2")
        string_found = True
        print line
    else:
        print line
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.