简体   繁体   中英

How to print from a loop onto a single line

The code:

for i in range(3):
    print '*'

prints:

*  
*  
*  

Is there anyway to print it so it is all on one line with no spaces in between?

A good chance to use the niceties of Python 3 with from __future__ :

from __future__ import print_function

for x in range(3):
    print('*', end='')

Output:

***

Now you ar using the Python 3 print() function in Python 2:

Docstring:

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments:

file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

You could also use:

print('*' * 3)

for the same output.

Adding a comma after the print stops python from adding a newline, so you need the following. Also for i in 3 isnt valid syntax, maybe you were thinking of range(3)?

for i in range(3):
    print '*',

to have no spaces between them just add a backspace character to the start

for i in range(3):
    print '\b*',

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM