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 04:51:25 EDT 2017
More information about the Python-list mailing list
Sat Sep 23 04:51:25 EDT 2017
- Previous message (by thread): search and replace first amount of strings instances with one thing and a second amount of instances with another thing-
- Next message (by thread): Issues with beginning Django use
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Bill wrote: > 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. I now realize that my last line does not apply. I suggest you start by just thinking about changing the first ten ones to twos. Once you do that, you should have little trouble finishing the job. Being a Python newbie myself, your example helped motivate me to try my own example. I used "type" to learn the data type of line (in your example), about which I was curious. My first concern was that is might only be "interable" object, but I learned that more is true. > > >> >> 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() >
- Previous message (by thread): search and replace first amount of strings instances with one thing and a second amount of instances with another thing-
- Next message (by thread): Issues with beginning Django use
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list