0

I have something like this (Python3):

for p in something:
  for r in something_else:
    print(r, end=" ")

but I want each last print in the inner loop to end with a newline to create a nice table. Is there some short and elegant way to do it?

1 Answer 1

1

Like this?

for p in something:
  for r in something_else:
    print("%s\t" % r, end=" ")
  print()

More elegant might be

for p in something:
  print(" ".join(map(str, something_else)))

Note that this will just print a table of the elements of something_else a bunch of times. What is in your list? How do you want the table to look? It might help if you're a little more specific in your question.

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

3 Comments

You can map(str, something_else) if it doesn't just contain strings.
Well, I need no whitespace (except the newline) after the last item in the row. something_else is a list of ints. I just need: 1 2 3 4newline 3 4 5 6newline etc. something_else in in fact a p (I have made an error above) and it is a list of ints. I just now use: ` i = 0 for r in p: i += 1 if i < n: print(r, end=" ") else: print(r)` which looks ugly (sorry cannot format the code properly in the comment)
" ".join(...) is what you are looking for - it places a space (" ") between each item in the passed list, and returns the resulting string. See my answer.

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.