5

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?

Anthony
  • 33,838
  • 42
  • 169
  • 278

3 Answers3

6

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

pkuphy
  • 314
  • 2
  • 9
3

why not use .format

s = """
uri1: {uri}/file1.txt
md5: {uri}
uri2: {uri}/file2.txt
md5: {uri}
uri3: {uri}/file3.txt
md5: {uri}
""".format(uri=self.URI)
stoebelj
  • 1,536
  • 2
  • 14
  • 31
3

You can use values more than once, for example:

"{0} {0} {1}".format("a", "b")
'a a b'
Philipp Claßen
  • 41,306
  • 31
  • 146
  • 239