Loading video player…

sep, end, and flush

In Python 3, print() is now a function and uses arguments to control its output. In this lesson, you’ll learn about the sep, end, and flush arguments.

By default, print() inserts a space between the items it is printing. You can change this by using the sep parameter:

Python
>>> print('There are', 6, 'members of Monty Python')
There are 6 members of Monty Python
>>> message = 'There are' + 6 + 'members of Monty Python'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> message = 'There are' + str(6) + 'members of Monty Python'
>>> print(message)
There are6members of Monty Python
>>> print('There are', 6, 'members of Monty Python', sep='😀')
There are😀6😀members of Monty Python
>>> print('There are', 6, 'members of Monty Python', sep=' ')
There are 6 members of Monty Python
>>> print('There are', 6, 'members of Monty Python', sep=None)
There are 6 members of Monty Python
>>> print('There are', 6, 'members of Monty Python', sep='')
There are6members of Monty Python
>>> print('There are', 6, 'members of Monty Python', sep='\n')
There are
6
members of Monty Python
>>> data = [ 
...     ['year', 'last', 'first'], 
...     [1943, 'Idle', 'Eric'], 
...     [1939, 'Cleese', 'John'] 
... ]
>>> for row in data:
...     print(*row, sep=',')
... 
year,last,first
1943,Idle,Eric
1939,Cleese,John

Unless told otherwise, print() adds a \n at the end of what is being printed. This can be changed with the end parameter. Output from print() goes into a buffer. When you change the end parameter, the buffer no longer gets flushed. To ensure that you get output as soon as print() is called, you also need to use the flush=True parameter:

Python
import time

def count_items(items):
    print('Counting ', end='', flush=True)
    num = 0
    for item in items:
        num += 1
        time.sleep(1)
        print('.', end='', flush=True)

    print(f'\nThere were {num} items')

You can combine sep and end to create lists, CSV output, bulleted lists, and more.

00:00 In the previous lesson, I gave a quick introduction to string formatting. In this one, I’ll be talking about the arguments that you can pass to print() to change how print() functions: sep, end, and flush.

00:15 As I showed you in the first lesson, print() can take multiple arguments. Here, I’m putting in a string, an integer, and a string, and print() puts it all out to the screen.

00:26 Notice that it’s not just concatenating those values. If I try to concatenate them using the plus operation (+), I get an error. That’s because Python is strongly typed.

00:38 You cannot add an integer to a string. You can call the built-in method str() to convert something to a string, which is what print() is doing underneath.

00:53 Well, it’s doing a little more than that, obviously. In addition to converting everything to strings, it’s also putting a space (' ') in between these pieces.

01:02 You can control what character it puts between the strings using the sep argument. Let’s have a little fun and change the sep to a happy happy little face.

01:15 Of course, the default is actually a space (' ').

01:24 That’s the same as if you did not specify the sep argument. You can also set its value to None. None is the same as space (' ') in this case.

01:35 It causes the default to be used.

01:40 Oftentimes, what you really want to do is get rid of the separator. You can do that simply by passing in an empty string (''). It doesn’t make sense for our sentence here, but if you’re trying to avoid the addition of the spaces inside of your printing, this is how you do it.

02:00 Escape sequences are just as valid. Here is '\n', and that gives us multiple lines of output. One possible use of this is to create CSVs. Let me put in some data…

02:18 and now a for loop. The asterisk (*) in front of row here takes the row value—which will be a single row from the data array—and passes it in as separate parameters, separate arguments to print(). For example, when it’s processing the first row—containing 'year', 'last', and 'first'*row is the equivalent of passing in 'year', 'last', 'first' and then the separator of comma (,). By doing this, you can see a CSV-style file being printed to the screen.

03:00 In case you haven’t come across this before, being able to pass in multiple arguments to Python is something built into functions—there’s nothing magic going on here specific to print(). The signature of print() takes *objects.

03:13 *objects, in this case, is treated as a list inside of the print() function, and the calling signature says you can pass in as many arguments as you like that are unnamed.

03:25 The consequences of this is the rest of the arguments after objects have to be named, because otherwise Python doesn’t know where the unnamed arguments stop and the named ones begin. You can use this mechanism even when you define your own functions. Let’s look at another argument that print() takes—the end argument. By default, print() puts a '\n' on the end of whatever string you are asking it to print before sending it to the screen.

03:52 You can change that by passing in the end argument. On line 3 and line 7 I’m going to set this so it prints no '\n'—just an empty string ('').

04:03 I’ve done this by creating a function called count_items() inside of a file called count_items. I’m going to import that…

04:15 create some data…

04:20 and now I’m going to call the function.

04:25 And there it is. Counting ... 3 items. You’ll notice this happened very quickly. There isn’t a lot of processing going on inside of this function.

04:33 Let’s pretend that there was more work that needed to be done. I’m going to simulate that by pausing, using the sleep() method. I’ll add some code, import the time library, and time.sleep() will wait for 1 second when it executes. Just a quick note: if you’re following along in the REPL, in order to use this changed code, you’ll have to exit the REPL and come back in in order to reload the function.

04:57 Python caches the functions that are in there—it doesn’t automatically reload it from the file. Here I go. Re-call count_items(). You’ll notice it paused for three seconds and then came out all at once.

05:10 This is probably not the effect that you’re looking for. The reason for this is print() actually puts the strings into a buffer. When it encounters the \n, it flushes that buffer and sends it to the screen. As a result, by taking the \n’s off the end of the print, you no longer see this, so everything gets put to the buffer and then the buffer gets put to the screen when line 12 is called. This isn’t really the intention I have. I want to show dot dot dot (...) as the work is happening.

05:42 I’m going to make some more changes to the code—this time adding a new argument, which is flush. flush flushes the buffer. So if you’ve modified the end argument, you usually want to add flush=True in addition. Let’s this in action…

06:03 and the function returns a dot (.) each time the print() is called, and it looks like a little progress mechanism. Changing the value of the end argument changes when things are put in the buffer, versus when things are put to the screen, as well as how they’re combined together. In the function sentences() defined above, the first two lines will be printed to the buffer, the third line—because end isn’t changed—will cause the '\n' to be appended to the string and the buffer to be sent to the actual output.

06:32 This combines our first, second, and third sentences into one long string on the screen. You can combine the sep and end arguments together to create comma-separated lists. The first and second print() functions here will put things into the buffer with commas between the words and commas at the end, and the third print() puts commas between the words and flushes the buffer with a '\n'.

06:59 This last example shows you how you can combine '\n' with other characters to make things look like a bullet list.

07:11 Up until now, I’ve only been printing to the screen. This is called the stdout (standard out) stream. There are more streams than this, and you can also print to files. In the next lesson, I’ll show you how.

Avatar image for Chris James

Chris James on May 9, 2020

You can, of course do this;

print('one', 'two', 'three', 'four', sep='\a')

And make your computer go ‘bonk’ three times. Satisfying. ☺️

Become a Member to join the conversation.