如果我在Python中有这样的字符串,我该如何填充占位符?
s = """
uri1: %s/file1.txt
md5: %s
uri2: %s/file2.txt
md5: %s
uri3: %s/file3.txt
md5: %s
"""
uri
将保持不变,但md5
会发生变化。因此,对于上述情况,最终输出将是这样的:
uri1: file:///somepath/foo/file1.txt
md5: 1234
uri2: file:///somepath/foo/file2.txt
md5: 4321
uri3: file:///somepath/foo/file3.txt
md5: 9876
我知道我可以填写每个%s
,但如果我不想每次都复制相同的变量怎么办?即我想避免这样做:
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)
在上面,我每次都必须指定self.URI
...我想知道是否有办法只能指定一次?
答案 0 :(得分:2)
结帐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)
这是一个帮助的页面。 https://pyformat.info
答案 1 :(得分:1)
为什么不使用.format
s = """
uri1: {uri}/file1.txt
md5: {uri}
uri2: {uri}/file2.txt
md5: {uri}
uri3: {uri}/file3.txt
md5: {uri}
""".format(uri=self.URI)
答案 2 :(得分:1)
您可以多次使用值,例如:
"{0} {0} {1}".format("a", "b")
'a a b'