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

时间:2019-01-08 15:52:10

标签: python python-3.x string format

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

print("Hello this is {} and {} and {} - Hello this is {} and {} and {} ".format(versionP, versionS, versionT, versionP, versionS, versionT))

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

2 个答案:

答案 0 :(得分: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'

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

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

答案 1 :(得分:5)

Python 3.6

我觉得它很简单:

print(f"Hello this is {versionP} and {versionS} and {versionT} - 
        Hello this is {versionP} and {versionS} and {versionT}")

您甚至可以在f格式或evaluate中使用nested f-strings方法