search and replace first amount of strings instances with one thing and a second amount of instances with another thing-

Bill BILL_NOSPAM at whoknows.net
Sat Sep 23 03:48:56 EDT 2017


validationmail1 at gmail.com wrote:
> i have a code in python to search and replace what i need though is to replace the first say 10 instances of the number 1 with 2 and the second 10 instances with the number 3. anybody knows how to do that?
Do you mean the (integer) number 1 or the character '1'? For instance, 
if the first line of the file is:
"There were 100 cats in the yard."
Do you want to change this to
"There were 200 cats in the yard."?
Remember that string objects are "immutable" so your code probably 
wouldn't work exactly like that.


>
> fin = open(r'F:\1\xxx.txt')
> fout = open(r'F:\1\xxx2.txt', "wt")
> for line in fin:
>      fout.write( line.replace('1', '2') )
> fin.close()
> fout.close()




More information about the Python-list mailing list