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?
答案 0 :(得分:2)
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.
答案 1 :(得分:1)
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*',