简体   繁体   中英

The end=' ' option in print function in python

I tried running the following program:

for i in range(5):
  print(i, end=' ')

However, it waits for me to write some string in the next line and gives the output like:

0 1 2 3 4 'Hi'

where 'Hi' is what I input. I'm using the latest version 3.6.5 and can't seem to understand the reason behind this error. Can anyone help?

The default value for end is '\\n' , meaning that print() will write a newline character after printing the arguments. This would put the cursor on the next line.

Usually, stdout (to which print() writes by default) is also line buffered , meaning that data written to it is not flushed (and shown on your terminal) until a newline character is seen, to signal the end of the line.

You replaced the newline with a space, so no newline is written; instead a space is written, letting you write successive numbers one after the other on the same line.

Add an extra, empty print() call after your for loop to write the newline after looping:

for i in range(5):
    print(i, end=' ')

print()

You could also add flush=True to the print(..., end=' ') calls to explicitly flush the buffer.

Alternatively, for a small enough range() , pass in the values to print() as separate arguments, leaving end at the default. Separate arguments are separated by the sep argument, by default set to a space:

print(*range(5))

The * in front of the range() object tells Python to loop over the range() object and pass all values that produces as separate arguments to the print() call; so all 5 numbers are printed with spaces in between and a newline character at the end:

>>> print(*range(5))
0 1 2 3 4

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