8

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?

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

Comments

5

You can use values more than once, for example:

"{0} {0} {1}".format("a", "b")
'a a b'

Comments

5

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)

Edit, 2024

f-strings are the modern way to do it now:

uri = self.URI
s = f"""
uri1: {uri}/file1.txt
md5: {uri}
uri2: {uri}/file2.txt
md5: {uri}
uri3: {uri}/file3.txt
md5: {uri}
"""

https://docs.python.org/3/tutorial/inputoutput.html#fancier-output-formatting

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.