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 string, the print command seems to always print numbers in rows.

Example

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

:

 1 2 ... 

required output is 1 2 3 4 5

I would be grateful for your help. Postscript I searched the Internet here and most of the questions were related to Python 2.7.

+6
source share
4 answers

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

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

Or you should probably just use:

 print('\t'.join(map(str, [1, 2, 3, 4, 5]))) 
+10
source

In addition to the other answers, there is a neat way to do this now when printing is a function:

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

Unlike your source code, this will not put a tab in front of the first number. If you want this extra tab, the easiest way is to simply put an empty element in front of the numbers, so it creates an additional tab separator:

 print('', *numbers, sep='\t') 
+7
source

You can use .join() to join them using a tab character:

 >>> numbers = [1, 2, 3, 4, 5] >>> print('\t'.join(map(str, numbers))) 1 2 3 4 5 

map(str, numbers) is identical to [str(n) for n in numbers] .

+4
source

You can use sys.stdout.write() instead of print() , which immediately sends your output to the output stream without a new line.

This flaw has an ugliness and the advantage is that you do not store your entire string in memory at once. (The join approach will crash your computer if your array was very, very large.)

+2
source

Source: https://habr.com/ru/post/927016/


All Articles