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?
Python String replace() Method The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.
The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value.
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
You can use values more than once, for example:
"{0} {0} {1}".format("a", "b")
'a a b'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With