Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Printing and Formatting

00:00 In the previous lesson, I wrapped up the section on iterables. In this section, I’ll cover formatting and printing text to the screen through built-in functions.

00:09 It’s a tradition in programming for the first piece of code you write when learning a new language to be “Hello world”. I suspect since you’re doing a deep dive on every built-in function in Python, you’ve probably seen print() before.

00:23 But it is a surprisingly deep function with more arguments than you might be familiar with. If your first Python version was 3.6 or later, you probably started string formatting with f-strings.

00:35 That’s definitely the way to go, but there is also a built-in function as well. As you’ve seen elsewhere, sometimes the functional approach solves certain problems that the built-in language feature can’t do.

00:46 Let’s go off to the REPL, and I’ll show you how to use some of the more esoteric parts of print() and how to format content as well.

00:55 I’ll start out with the basic “Hello world”, so you can see the effects of some of the other arguments.

01:01 No surprise there, I hope. You can pass multiple arguments to print(). When you do, each gets printed separated by a space. So whether that was one string or two, you get to the same output.

01:15 The value put between the arguments is known as the separator. It defaults to a single space, but you can change it to another string using the sep argument.

01:29 That can be more than one character if you like as well, any string you need. The most common use of sep is to set it to empty when you’re printing out multiple things that you don’t want separated by spaces.

01:41 By default, print() issues a newline after outputting your content. That’s why the REPL prompt is after the printed value, because it’s actually printing the string and then a newline.

01:51 Like with sep, this can be controlled, this time by setting the end argument.

02:00 Setting end to three newlines gives you lots of space before the next prompt. I’d say my most common use of end is setting it to empty.

02:10 Consider the following loop.

02:17 Since end was the empty string, all the numbers get printed right after each other. Unfortunately, that also means there’s no end line after the content either, which is why my first REPL prompt got squished over like that.

02:31 Let’s leave off printing for a moment. The most common way of doing formatting in Python is with an f-string, but it isn’t the only way. Although Python tries to have a single way to do a thing, it’s part of the Zen of Python and tends to make it easier to learn, it doesn’t always stick to that.

02:48 Formatting has changed over the years, and for backward compatibility, all the ways of formatting strings are still there. Since this is a course on the built-in functions, I’m going to cover one alternative, the format() function.

03:01 First, I need something to format, so let me import math so I can get at pi. This is pi in Python without any formatting.

03:10 Python may be powerful, but it still limits the digits of pi. Otherwise, you’d be here forever watching it print out. Oh, and there’s that running out of memory thing.

03:19 Let’s shorten it to even fewer digits.

03:24 The format() function takes two arguments, the thing to format and the format specifier. The specifier is itself a string that says what formatting to do. There’s a little mini-language in Python that gives you lots of control, and it’s mostly consistent between the different formatting mechanisms.

03:42 Here, .4f says to format as a floating-point with four digits after the decimal, hence 3.1416.

03:53 Using e as the formatter specifies the use of scientific notation. Everything after the plus is the exponent that you raise to 10 in scientific notation.

04:03 Since pi only has a ones column, the 10 is 0 in this case.

04:10 Adding a comma to the formatter does thousands separation. Also note, although I sent in an integer, I set to show two decimal places, so you get two decimal places.

04:22 This one’s common for printing money to the screen.

04:27 The less than sign says to pad the string to the left. This is useful for fixed-length fields. Note the output string is 30 characters long, even though Bob Smith is shorter than that.

04:41 The caret symbol says to center a value, and the thing to the left of the caret is the fill character, thus giving us Header in the middle surrounded by equal signs.

04:52 format() can handle dates as well. Let me get the datetime module.

05:01 The percents here indicate the short form of the day and month, then the date, then the year. At the end of this lesson, I’ll link to an article on the full set of features the mini formatting language supports.

05:13 There are two more arguments to print() that I haven’t covered yet, one of which we’ll wait for the next lesson. The other is flush.

05:21 When you print to the screen, Python is actually filling a buffer in memory first, which it then decides when to put out to the screen. This is known as flushing.

05:30 It does this rather than print a single character at a time to save on the number of system calls that need to be done. By default, the flush argument is set to False, letting Python control when to send the print buffer to the screen.

05:44 Most of the time, you don’t care about this. The buffer gets flushed when you expect it to, and your line gets printed, but sometimes you want to control it.

05:53 Let me show you a little example where I want finer-grain control. I’m going to write a little bit of screen animation. This function will print a progress bar to the screen.

06:04 It takes an integer as an argument, specifying how far along the progress is.

06:14 To do the animation step, I need to be able to wipe the current line on the screen and replace it with a new one. That means I can’t have a newline on the end, otherwise I’d be on to the next line. Instead, I want to overwrite the current line.

06:29 This bit of code checks if the progress bar is complete. If so, use a newline. Otherwise, no newline for you.

06:42 Here, I’m calculating the length of the progress bar, printing a number of hash characters. The full length is 30 characters long, hence the 30 * percent part, then divided by 100 to turn it into something respecting our percentage.

07:01 I want the inside part of the progress bar to be the same length each time, so here I’m using format() to left align my bar in a 30-character space.

07:20 And then finally, this is the print(). It’s a lot. Let’s go over it one argument at a time. The \r character means to return to the beginning of the line.

07:31 This combined with an empty end is what overwrites any existing line, giving us a little flipbook-style animation replacing each line with the next progress bar output.

07:43 The square bracket in the string is just a square bracket. I’m putting those around the hash part of the progress bar. The second argument is middle, that’s the actual graph thingy.

07:54 Then, another square bracket and a space. I’m going to use an empty value for sep, so I have to manually include this space to make sure there’s a space between the square bracket and the next part. Next, I’m using format() again, this time to show the percent progress as a number.

08:11 I’ve chosen to use zero decimal places, although you might be passing in an integer, you could also pass in a float and it would still work out the same. After that comes the percent symbol to go with the number I just printed, and then I’m going to control how print() works.

08:27 I set sep to empty so that there are no extra spaces between all those things I just talked about, and then I set the value of end to my end variable, controlling whether or not there’s a line feed, and finally, what you came for, setting flush to True. You don’t want Python deciding when to buffer your output here.

08:46 You want to control it. You want to force it to flush each time it generates a line. If not, your animation could skip steps or not happen at all. All right, let’s test this out.

08:58 First, to slow the animation down a bit, I’m going to put the code to sleep() in each loop.

09:06 I’m looping from 1 to 100, going up by 3.

09:10 Each loop will sleep for 0.05 of a second.

09:15 Then I call our function.

09:19 And there’s the result, a progress bar animation.

09:23 For more examples on using the different arguments to print(), check out this video course or tutorial. While this tutorial covers the mini-format language in depth used by the format() function as well as f-strings.

09:37 Or if you’d like to see more examples of using flush, check this one out.

09:43 You’ve seen some output, so next up, it’s only fair, input.

Become a Member to join the conversation.