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
>>> s = 'qwerrqweqweasdqweqwe*replacethistext*asdasdasd'
>>> s.replace('*replacethistext*', '*withthistext*')
'qwerrqweqweasdqweqwe*withthistext*asdasdasd'
import string
for line in file:
print string.replace(line, "replacethistext", "withthistext")
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
fp = open(filename, 'r')
outfp = open(outfilename, 'w')
for line in fp:
outfp.write(line.replace('*replacethistext*', '*withthistext*'))
fp.close()
outfp.close()
精彩评论