python中带有变量的新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36780514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:19:51  来源:igfitidea点击:

new line with variable in python

pythonpython-3.xnewlinecombinationsline-breaks

提问by user6234753

When I use "\n"in my printfunction it gives me a syntax error in the following code

当我"\n"在我的print函数中使用时,它在下面的代码中给了我一个语法错误

from itertools import combinations
a=[comb for comb in combinations(range(1,96+1),7) if sum(comb) == 42]
print (a "\n")

Is there any way to add new line in each combination?

有没有办法在每个组合中添加新行?

回答by ShadowRanger

The printfunction already adds a newline for you, so if you just want to print followed by a newline, do (parens mandatory since this is Python 3):

print函数已经为您添加了一个换行符,因此如果您只想打印后跟一个换行符,请执行(括号是必需的,因为这是 Python 3):

print(a)

If the goal is to print the elements of aeach separated by newlines, you can either loop explicitly:

如果目标是打印a由换行符分隔的每个元素,您可以显式循环:

for x in a:
    print(x)

or abuse star unpacking to do it as a single statement, using septo split outputs to different lines:

或滥用星形解包将其作为单个语句执行,sep用于将输出拆分为不同的行:

print(*a, sep="\n")

If you want a blank line between outputs, not just a line break, add end="\n\n"to the first two, or change septo sep="\n\n"for the final option.

如果你想输出之间添加一个空白行,而不仅仅是一个换行符,end="\n\n"改变了前两个,或sepsep="\n\n"了最后的选项。

回答by PfunnyGuy

Two possibilities:

两种可能:

print "%s\n" %a
print a, "\n"

回答by Garrett R

This will work for you:

这对你有用:

I used 1,2...6 in my example and 2 length tuples with a combination sum of 7.

我在我的例子中使用了 1,2...6 和 2 个长度为 7 的元组。

from itertools import combinations
a=["{0}\n".format(comb) for comb in combinations(range(1,7),2) if sum(comb) == 7]

print(a)
for thing in a:
    print(thing)

Output

输出

['(1, 6)\n', '(2, 5)\n', '(3, 4)\n']
(1, 6)

(2, 5)

(3, 4)

回答by fastlan

for me in the past something like print("\n",a) works.

过去对我来说,像 print("\n",a) 这样的东西是有效的。