0

所以我有以下内容:

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))

?

4

3 回答 3

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()功能(和相关功能)已经完成的功能。

于 2013-08-14T10:04:42.173 回答
1

我正在使用 python 2.7 但这与您正在寻找的内容非常接近和整洁

我正在使用*or 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.
于 2013-08-14T10:02:26.587 回答
0

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

print "这是 %s 字符串。它有 %s 替换。" %("一些", "两个")

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

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

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


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

于 2013-08-14T11:18:28.827 回答