2

I have a list of paragraphs like this:

list1 = [
  "something",
  "more",
  ...
  "{ //image// }"
  "something"
  ...
  "{ //image// }"
  ...
]

The "{ //image// }" text occurs a known amount in the list. I have another list with paths to images which has the same length as the amount of occurrences of the text:

list2 = [
  "path1",
  "path2"
]

Now I am working with pyqt and I want to show all the elements of the first list in a QLabel. I am doing this like that:

paragraphs = ""
for element in list1:
    elements += element + "<br>"
my_QLabel.setText(elements)

Now I want to replace every occurrence of the String { //image// } in the QLabel with an image from the second list. How can I do that while still keeping the other text?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
SdahlSean
  • 573
  • 3
  • 13
  • What relationship does "{// image //}" have with "path1", or with "path2"? How do you select that "{// image //}" is related to path1 or path2? – eyllanesc Apr 27 '19 at 04:02
  • The first { //image// } is replaced by the first image in the paths list, the second by the second and so on. – SdahlSean Apr 27 '19 at 04:05

1 Answers1

1

Assuming that the amount of {// image //} in the first list matches the length of the second list. In this case you can implement a logic to replace:

from PyQt5 import QtCore, QtGui, QtWidgets


def build_text(texts, images, word):
    image_format = """<img src="{}" width="100" height="100">"""
    images_iter = iter(images)
    text = "<br>".join(
        [
            image_format.format(next(images_iter)) if e == word else e
            for e in texts
        ]
    )
    return text


if __name__ == "__main__":
    import sys

    list1 = [
        "something",
        "more",
        "{ //image// }",
        "something",
        "{ //image// }",
        "{ //image// }",
        "more",
        "{ //image// }",
    ]

    list2 = [
        "/path/of/image1.png",
        "/path/of/image2.png",
        "/path/of/image3.png",
        "/path/of/image4.png",
    ]
    app = QtWidgets.QApplication(sys.argv)
    w = QtWidgets.QLabel()
    text = build_text(list1, list2, "{ //image// }")
    w.setText(text)
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241