Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a list of numbers in python v.3

I am using Python version 3.2.3. I am trying to print a list of numbers in a row, the print command seems to always printing the numbers one at row.

Example

numbers = [1, 2, 3, 4, 5];
for num in numbers:
    print("\t ", num)

output is:

1

2
...

the required output is 1 2 3 4 5

I would appreciate your help. P.s. I searched the web in here and most of the questions were related to Python 2.7.

like image 459
Sinan Avatar asked Oct 05 '12 08:10

Sinan


2 Answers

Use the end argument to suppress (or replace) the automatic EOL output:

print("\t ", num, end='')

Or, you should probably just use:

print('\t'.join(map(str, [1, 2, 3, 4, 5])))
like image 124
Jon Clements Avatar answered Sep 21 '22 15:09

Jon Clements


In addition to the other answers, there's a neat way to do it now that print is a function:

print(*numbers, sep='\t')

Unlike your original code, this won't put a tab before the first number. If you want that extra tab, the easiest way is just to put a blank item before the numbers, so it creates an extra tab separator:

print('', *numbers, sep='\t')
like image 29
Thomas K Avatar answered Sep 19 '22 15:09

Thomas K