user758415
user758415

Reputation: 1

How do I replace part of a large string in Python?

I have a file with multiple lines, each having a long sequence of characters (no spaces).

For example in one line:

qwerrqweqweasdqweqwe*replacethistext*asdasdasd

qwerrqweqweasdqweqwe*withthistext*asdasdasd

The specific string I am looking for can happen any where in a certain line.

How would I accomplish this?

Thanks

Upvotes: 0

Views: 480

Answers (4)

Acorn
Acorn

Reputation: 50517

>>> s = 'qwerrqweqweasdqweqwe*replacethistext*asdasdasd'
>>> s.replace('*replacethistext*', '*withthistext*')
'qwerrqweqweasdqweqwe*withthistext*asdasdasd'

Upvotes: 7

Evan Cortens
Evan Cortens

Reputation: 790

fp = open(filename, 'r')
outfp = open(outfilename, 'w')
for line in fp:
    outfp.write(line.replace('*replacethistext*', '*withthistext*'))
fp.close()
outfp.close()

Upvotes: 1

Rafe Kettler
Rafe Kettler

Reputation: 76955

line = "qwerrqweqweasdqweqwe*replacethistext*asdasdasd"
line = line.replace("*replacethistext*", "*withthistext*")

You can do this with any string. If you need substitutions with regexp, use re.sub(). Note that neither happens in place, so you'll have to assign the result to a variable (in this case, the original string).

With file IO and everything:

with open(filename, 'r+') as f:
    newlines = [] 
    for line in f:
        newlines.append(line.replace(old, new))
    # Do something with the new, edited lines, like write them to the file

Upvotes: 1

Borealid
Borealid

Reputation: 98489

import string
for line in file:
    print string.replace(line, "replacethistext", "withthistext")

Upvotes: 1

Related Questions