0

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

3
  • 1
    how large is a large string? if we are talking about huge files, for example, then you will probably want to read the file in chunks, but your replacement algoritm will have to check if it is chunking inside a replace text. Commented May 18, 2011 at 2:13
  • What part of string.replace() confused you? Commented May 18, 2011 at 2:49
  • Keep in mind that strings are immutable. Commented May 18, 2011 at 3:26

4 Answers 4

7
>>> s = 'qwerrqweqweasdqweqwe*replacethistext*asdasdasd'
>>> s.replace('*replacethistext*', '*withthistext*')
'qwerrqweqweasdqweqwe*withthistext*asdasdasd'
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Ewww.... why wouldn't you use the method? You really should almost never have to import string.
Only use this if you need to be backward compatible with Python1.x!
1
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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.