How to change a string in a file to strings froma a list
file, list, python, string
Solution
A simple, but not very efficient way would be to replace the tags one at a time:
>>> li = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]
>>> s = "a tag [[Media:]] - I want to replace all [[Media:]] tags with a names of pictures stored in a list. For example in a converted document there will be 5 [[Media:]] tags d by a tag [[Media:]] - I want to replace all [[Media:]] tags"
>>> for item in li:
... s = s.replace("[[Media:]]", item, 1) # max. 1 replace per call
...
>>> s
'a tag image1.jpg - I want to replace all image2.jpg tags with a names of pictures stored in a list. For example in a converted document there will be 5 image3.jpg tags d by a tag image4.jpg - I want to replace all image5.jpg tags'
A better way would be to construct the string in one go:
def interleave(original, tag, replacements):
items = original.split(tag)
return "".join((text+repl for text,repl in zip(items, replacements+[""])))
Use it like this:
>>> interleave(s, "[[Media:]]", li)
'a tag image1.jpg - I want to replace all image2.jpg tags with a names of pictures stored in a list. For example in a converted document there will be 5 image3.jpg tags d by a tag image4.jpg - I want to replace all image5.jpg tags'
Problem
I'am really new to Python programming and I have this burning problem with changing a specific string in a text file with a strings which are stored in a list. I'am working on media wiki documents - converting them from .doc to wiki code. After a conversion all images are replaced by a tag [[Media:]] - I want to replace all [[Media:]] tags with a names of pictures stored in a list. For example in a converted document there will be 5 [[Media:]] tags so it means that I have list like this: ``` li = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"] ``` And I want to change first tag in document to bo replaced with image1.jpg, the second tag found in document with image2.jpg and so on.. Here is a piece of code, but I can not figure how to make iteration through list to work ``` li = ["image1.jpg ", "image2.jpg ", "image3.jpg ", "image4.jpg ", "image5.jpg "] a = 0 src = open('sap.txt').readlines() dest = open('cel.txt', 'w') for s in src: a += 1 dest.write(s.replace("[[Media:]]", li[a])) dest.close() ``` I will be grateful for help