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?

10
  • 2
    Where are you using "\n"? Commented Apr 21, 2016 at 21:08
  • print (a "\n") like this @mprat Commented Apr 21, 2016 at 21:09
  • @user6234753 you make wrong concatenation of the string. Checkout this Commented Apr 21, 2016 at 21:11
  • 1
    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? Commented Apr 21, 2016 at 21:24
  • 1
    @user6234753 for combination in a: print(combination) will do what you want. Commented Apr 21, 2016 at 21:32

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Two possibilities:

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

Comments

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.