Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace placeholders in python strings

Tags:

python

string

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?

like image 503
Anthony Avatar asked Apr 15 '17 14:04

Anthony


People also ask

What does replace () do in Python?

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.

How do you use %s in Python?

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.


2 Answers

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

like image 174
pkuphy Avatar answered Sep 22 '22 11:09

pkuphy


You can use values more than once, for example:

"{0} {0} {1}".format("a", "b")
'a a b'
like image 24
Philipp Claßen Avatar answered Sep 22 '22 11:09

Philipp Claßen