new line with variable in python
Asked Answered
S

4

6

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

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?

Schluter answered 21/4, 2016 at 21:7 Comment(10)
Where are you using "\n"?Siloam
print (a "\n") like this @SiloamSchluter
@Schluter you make wrong concatenation of the string. Checkout thisUnspeakable
Is this Python 2 or Python 3?Idler
okay @sємsєм I will check itSchluter
Python 3 @EdwardMinnixSchluter
This is unrelated to the problem, but doing combinations of numbers up to 97 and then keeping only those combinations that add up to 42 is a waste of processing time. On topic, I'm also not sure printing a \n after a will improve the readability... maybe you want to print a new line after each combination?Crestfallen
change the combination to a different number I just want to make every combination in new line @PauloAlmeidaSchluter
@Schluter for combination in a: print(combination) will do what you want.Crestfallen
thank you so much @PauloAlmeidaSchluter
T
7

The print function 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(a)

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

for x in a:
    print(x)

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

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 sep to sep="\n\n" for the final option.

Turbulence answered 21/4, 2016 at 21:57 Comment(0)
B
3

Two possibilities:

print "%s\n" %a
print a, "\n"
Berlyn answered 21/4, 2016 at 21:12 Comment(0)
M
0

This will work for you:

I used 1,2...6 in my example and 2 length tuples with a combination sum of 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)
Majolica answered 21/4, 2016 at 21:35 Comment(0)
G
0

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

Gertrudgertruda answered 3/1, 2020 at 23:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.