Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我可以在打印语句中包含for循环吗?_Python_Python 3.x - Fatal编程技术网

Python 我可以在打印语句中包含for循环吗?

Python 我可以在打印语句中包含for循环吗?,python,python-3.x,Python,Python 3.x,我有一份活动获奖者名单。我想在代码末尾打印出来,减去括号和引号,我目前正在使用: for items in winners: print(items) 我可以在打印报表中包含这个吗? 我想: 是否有一种方法可以将for循环集成到print语句中,或者有另一种方法可以消除引号和方括号,以便我可以将其包含在语句中 谢谢。如果winners是字符串列表,您可以使用str.join将它们连接起来 例如: >>> winners

我有一份活动获奖者名单。我想在代码末尾打印出来,减去括号和引号,我目前正在使用:

            for items in winners:
                print(items)
我可以在打印报表中包含这个吗? 我想:

是否有一种方法可以将for循环集成到print语句中,或者有另一种方法可以消除引号和方括号,以便我可以将其包含在语句中


谢谢。

如果
winners
是字符串列表,您可以使用
str.join
将它们连接起来

例如:

>>> winners = ['John', 'Jack', 'Jill']
>>> ', '.join(winners)
'John, Jack, Jill'

因此,您可以在打印调用中加入(winners),而不是
winners
,它将打印以逗号分隔的winners。

您不能包含for循环,但可以将winners列表加入字符串

winners = ['Foo', 'Bar', 'Baz']
print('the winners were {}.'.format(', '.join(winners)))
这会打印出来

获胜者是福、巴、巴


for循环只能以理解的形式提供给
print

但是,如果列表内容按照您要求的顺序排列,您只需执行以下操作:

print("The winners of {} were: {} with a score of {}".format(*winners))
这只是将每个括号与列表中的每个项目相匹配。如果您需要以不同的方式订购,只需提供它们的相对位置:

print("The winners of {1} were: {0} with a score of {2}".format(*winners))

首先注意,在Python3中,print是一个函数,但在Python2中是一个语句。此外,不能将
for
语句用作参数。 我想到的只有这样一个奇怪的解决方案,它看起来就像一个for循环:

data = ['Hockey','Swiss', '3']
print("Sport is {}, winner is {}, score is {}".format(*( _ for _ in data )))
当然,因为
print
是一个函数,所以您可以使用所需的所有内容编写自己的函数,例如:

def my_print(pattern, *data):
    print(pattern.format(*( _ for _ in data)))  

my_print("Sport is {}, winner is {}, score is {}", 'Hockey', 'Swiss', '3')

您还可以阅读关于将在Python 3.6中引入的f-strings。此f-strings将提供一种在字符串文本中嵌入表达式的方法,使用最小语法。

请提供您正在处理的数据的准确示例,以及您期望其外观的示例。解释当前正在发生的事情,这表明您的代码有问题。@idjaw这是一个关于语言功能的问题,这不是一个关于代码问题的问题。@JeremyFriesner我不认为在这种情况下询问更多信息有什么错?肯定是尝试过了,但没有成功,这导致OP首先提出了这个问题?询问更多信息,帮助OP了解他们对我的错误,这是一个很好的方法。
def my_print(pattern, *data):
    print(pattern.format(*( _ for _ in data)))  

my_print("Sport is {}, winner is {}, score is {}", 'Hockey', 'Swiss', '3')