cplus
cplus

Reputation: 1115

Python line.replace multiple strings

I am replacing the '2010' with a random number:

from random import randint
with open("data.json", "rt") as fin:
    with open("dataout.json", "wt") as fout:
        for line in fin:
            fout.write(line.replace('2010', str(randint(1990, 2007))))

how can I replace two items in one code, that is:

fout.write(line.replace('2099', str(randint(1800, 1900))))
fout.write(line.replace('2010', str(randint(1990, 2007))))

Upvotes: 0

Views: 1111

Answers (2)

Kasravnd
Kasravnd

Reputation: 107297

Use two replace() method:

from random import randint
with open("data.json", "rt") as fin:
    with open("dataout.json", "wt") as fout:
        for line in fin:
            fout.write(line.replace('2010', str(randint(1990, 2007))).replace('2099', str(randint(1800, 1900))))

Upvotes: 1

ettanany
ettanany

Reputation: 19806

You just need to use if to check if your line contains '2099' or '2010' like this:

from random import randint

with open("data.json", "rt") as fin:
    with open("dataout.json", "wt") as fout:
        for line in fin:
            if '2010' in line:
                fout.write(line.replace('2010', str(randint(1990, 2007))))
            if '2099' in line:
                fout.write(line.replace('2099', str(randint(1800, 1900))))

Upvotes: 2

Related Questions