随后将替换插入%-string

时间:2013-08-14 09:55:51

标签: python

所以我有以下内容:

myString = "This is %s string. It has %s replacements."
myParams = [ "some", "two" ]

# This is a function which works (and has to work) just like that
myFunction(myString, myParams)

现在,当我调试时,我会执行以下操作:

print("Debug: myString = " + myString)
print("Debug: myParams = " + myParams)

但是我想直接在一个印刷品中得到它,例如:

"Debug: This is some string. It has two replacements."

这有可能吗?像

这样的东西
print("Debug: myString = " + (myString % myParams))

3 个答案:

答案 0 :(得分:5)

您需要使用元组;将您的列表转换为元组,并且运行正常:

>>> myString = "This is %s string. It has %s replacements."
>>> myParams = [ "some", "two" ]
>>> myString % tuple(myParams)
'This is some string. It has two replacements.'

myParams定义为开头的元组:

>>> myString = "This is %s string. It has %s replacements."
>>> myParams = ("some", "two")
>>> myString % myParams
'This is some string. It has two replacements.'

您可以将其组合成一个函数:

def myFunction(myString, myParams):
    return myString % tuple(myParams)

myFunction("This is %s string. It has %s replacements.", ("some", "two"))

或者更好的是,让myParams成为一个全能的参数,它总是解析为一个元组:

def myFunction(myString, *myParams):
    return myString % myParams

myFunction("This is %s string. It has %s replacements.", "some", "two")

后者是logging.log()函数(和相关函数)已经完成的。

答案 1 :(得分:1)

我正在使用python 2.7,但这与你正在寻找的东西非常接近和整洁

我正在使用*或splat运算符将列表解压缩为位置参数(或元组)并将该元组提供给format()并且可以使用myString变量上的格式将%s更改为{index}

>> myString = "This is {0} string. It has {1} replacements."
>> myParams = ["some", "two"]
>> print "Debug: myString = "+ myString.format(*myParams)
>> Debug: myString = This is some string. It has two replacements.

答案 2 :(得分:0)

实现您想要的最基本的打印语法如下:

print“这是%s字符串。它有%s替换。” %(“某些”,“两个”)

您可以将其格式化为某种功能(就像其他人之前回复过的那样),但我认为在了解最基本的打印语法时应该有价值。

字符串中的%s充当元组中存储的值的占位符。

您可以拥有其他占位符,例如浮点数(%f)等等。


仅供参考,从Python 3开始,有一种更新(更清晰)的打印格式。