Python打印包含两个变量的输出



我对Python非常陌生,并且使用现有的Python脚本,目前它输出一条消息,末尾标记有一个变量:

print "ERROR: did not find any details inside "{0}".format(filename)

我想在另一个变量中修改这个添加,以便输出为:

print "ERROR: did not find "{name}" inside "{file}""

在用变量替换{name}和{file}的情况下,实现这一点的正确方法是什么?

在Python 2中,可以使用format传递命名参数,并将名称插入变量中。请注意,您可以使用单引号或双引号对字符串进行引号引用,因此您可以通过使用单引号来避免必须转义双引号:

>>> name = 'John'
>>> file = 'hello.txt'
>>> print 'ERROR: did not find "{name}" inside "{file}"'.format(name=name,file=file)
ERROR: did not find "John" inside "hello.txt"

一个快捷方式是使用**运算符传递一个键/值对字典作为参数。locals()以这种格式返回所有局部变量,因此可以使用以下模式:

>>> name = 'John'
>>> file = 'hello.txt'
>>> print 'ERROR: did not find "{name}" inside "{file}"'.format(**locals())
ERROR: did not find "John" inside "hello.txt"

Python 3.6+使用f-string使其更干净:

>>> name = 'John'
>>> file = 'hello.txt'
>>> print(f'ERROR: did not find "{name}" in "{file}"')
ERROR: did not find "John" in "hello.txt"

您似乎在使用Python 2,因此正确的方法如下:

print "ERROR: did not find "{0}" inside "{1}"".format(name, file)

{0}表示从format()参数列表中取第一个参数,依此类推

在其他条件相同的情况下,最好使用Python 3和f-strings

.format是python中非常有用的方法。请查看此链接以更好地理解。https://www.w3schools.com/python/ref_string_format.asp我希望这些例子能帮助你很好地理解这个方法。

你也可以试试这个:

print "ERROR: did not find "{}" inside "{}"".format(name, file)
f"ERROR: did not find {name} inside {file}"

如果需要封装变量,只需要放入f,这意味着格式字符串,这样它就可以插入变量的值,而不仅仅是打印出来。

最新更新