避免重复str.format的相同参数

M.U*_*tun 3 python string format python-3.x

我目前在我的代码中使用字符串格式,但我发现我很难编码显示重复的变量.有没有更有效的方法来做到这一点

print("Hello this is {} and {} and {} - Hello this is {} and {} and {} ".format(versionP, versionS, versionT, versionP, versionS, versionT))
Run Code Online (Sandbox Code Playgroud)

结果是我想要的结果,但我需要在几个例子中重复这一点,并且可能变得单调乏味.有没有办法只写一次变量?

cs9*_*s95 6

您可以指定位置,并str.format知道要使用的参数:

a, b, c = 1, 2, 3
string = "This is {0}, {1}, and {2}. Or, in reverse: {2}, {1}, {0}"
string.format(a, b, c)
# 'This is 1, 2, and 3. Or, in reverse: 3, 2, 1'
Run Code Online (Sandbox Code Playgroud)

您也可以传递关键字参数,或解压缩字典:

a, b, c = 1, 2, 3
string = """This is {versionP}, {versionS}, and {versionT}. 
            Or, in reverse: {versionT}, {versionS}, {versionP}"""
# string.format(versionP=a, versionS=b, versionT=c)
string.format(**{'versionP': a, 'versionS': b, 'versionT': c})
# This is 1, 2, and 3. 
#       Or, in reverse: 3, 2, 1
Run Code Online (Sandbox Code Playgroud)


Aar*_*_ab 5

Python 3.6

我发现它干净简单:

print(f"Hello this is {versionP} and {versionS} and {versionT} - 
        Hello this is {versionP} and {versionS} and {versionT}")
Run Code Online (Sandbox Code Playgroud)

您甚至可以评估 f格式化或嵌套f字符串中的方法