pythonstring

How to replace placeholders in python strings


If I have a string like this in Python, how can I fill the placeholders?

s = """
uri1: %s/file1.txt
md5: %s
uri2: %s/file2.txt
md5: %s
uri3: %s/file3.txt
md5: %s
"""

The uri will remain same, however, md5 will change. So for the above, the final output would be something like this:

uri1: file:///somepath/foo/file1.txt
md5: 1234
uri2: file:///somepath/foo/file2.txt
md5: 4321
uri3: file:///somepath/foo/file3.txt
md5: 9876

I know I can fill every %s but what if I don't want to duplicate the same variable each time? i.e. I want to avoid doing this:

s = """
uri1: %s/file1.txt
md5: %s
uri2: %s/file2.txt
md5: %s
uri3: %s/file3.txt
md5: %s
""" % (self.URI, self.md5_for_1, self.URI, self.md5_for_2, self.URI, self.md5_for_3)

In the above, I have to specify self.URI each time...I'm wondering if there is a way to be able to just specify it once?


Solution

  • Check out str.format:

    string = """
    uri1: {s.URI}/file1.txt
    md5: {s.md5_for_1}
    uri2: {s.URI}/file2.txt
    md5: {s.md5_for_2}
    uri3: {s.URI}/file3.txt
    md5: {s.md5_for_3}
    """.format(s=self)
    

    Here is a page to help. https://pyformat.info