Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Basic Usage and String Literals

If you’re like most Python users, including us, then you probably started your Python journey by learning about print(). It helped you write your very own Hello Horld one-liner. You can use it to display formatted messages onto the screen and perhaps find some bugs. But if you think that’s all there is to know about Python’s print(), then you’re missing out on a lot!

Keep reading to take full advantage of this underappreciated little function. This course will get you up to speed with using Python print() effectively. Prepare for a deep dive as you go through the sections. You may be surprised how much print() has to offer!

By the end of this course, you’ll know how to:

  • Avoid common mistakes with Python’s print()
  • Deal with newlines, character encodings, and buffering
  • Write text to files
  • Mock print() in unit tests
  • Build advanced user interfaces in the terminal

Download

Sample Code (.zip)

23.3 KB

Download

Course Slides (.pdf)

783.5 KB

00:00 Welcome! This course is on the print() function in Python. My name is Chris, and I will be your guide. I will be covering how string literals work in Python; how to format those strings and use them inside of print(); the sep, end, and flush arguments that have been introduced in the new print() function in Python 3; how to print to files and streams besides just to stdout (standard out); how to adjust your own data types so they look better when they’re printed; what changed in print() between Python 2 in Python 3 and the advantages you can use now that print() is a built-in function; the alternative to print(), the pretty print command; how to use ANSI escape sequences to colorize and add bold and underline to your text; using control characters to produce simple line animation; how to mock print() inside of unit tests; how to use print() inside of debugging; and then finally, I’ll talk a little bit about other places you can go to improve your output game. A quick note, before I start: print() is one of the more obvious changes between Python 2 and Python 3. print used to be a built-in keyword statement and is now a built-in function. Lesson 6 talks about specific differences, but elsewhere, all of the examples are in Python 3, so the code you see won’t work in a Python 2 environment.

01:18 Let’s start with the simplest example—just typing print() into the REPL.

01:24 It returns an empty line. That’s because print() expects a string and then appends a newline after it. Something a little more useful—printing a greeting…

01:36 and there you go. The output is whatever string was passed to print(). You can also pass multiple arguments to print()—not just strings, but numbers or other kinds of objects. print() converts them to strings and then prints out the output. Strings are how you interface with text in your code.

01:55 There are three ways of declaring a string inside of Python. The first is to use double quotes ("), the second is single quotes ('), and the third is triple quotes (""").

02:05 Triple quotes allow you to represent multiline strings. Personally, I use single quotes, but the Python style guide says to be consistent. Triple quotes are also used to create docstrings inside of your code.

02:19 Supporting the two kinds of quotes makes it easy to put quotes inside of strings. For example, this first sentence has an apostrophe in it. I don’t have to do anything special, because the double quotes on the outside allow me to put the single quote on the inside without making any differences.

02:36 Likewise, by putting a string with single quotes on the outside, I can put the double quotes on the inside without having to do anything special.

02:44 This can be particularly helpful if you’re showing HTML where there’s a lot of quotes inside of the HTML itself.

02:52 Let’s look at that inside of the REPL. I’ll start with a double-quote string. Enter it in. Python, interestingly enough, shows that in the REPL as a single quote, but it’s showing you the string I’ve just entered.

03:05 Same thing happens if I do it with single quotes. With a multiline quote, the REPL stops when I hit Enter, allows me to keep typing on my multiple bits of input until I close it with the triple quotes.

03:19 It returns that as a single quote with \n’s inside of it where my new lines were. Let’s take a closer look at that. Here’s the code I just entered inside of the REPL.

03:32 You’ll notice that it returns with these \n’s. What’s a \n? This represents what’s called a newline. Different operating systems handle this character differently, but Python abstracts that away for you.

03:46 The newline character creates a new line in your output, returning the cursor to the beginning. By default, print() automatically adds one of these to the end of any string that it prints.

03:57 So if I was going to print that string that is in the code above, a third newline would show up after the word 'lines',

04:05 returning the cursor to the beginning. \n isn’t the only special character. These slash ( \ ) characters are called escape characters. Newline (\n) does a return to the beginning. Tab (\t) shows a tab.

04:19 ASCII bell (\a) actually plays a little “boonk” sound. You can put in octal or hex character values by using the \o or \x escape.

04:30 If you actually have a slash ( \ ) that you need to put in, writing a slash ( \ ) is slash slash ( \\ ). You can also escape quotes. Slash double quote (\") and slash single quote (\') allow you to put a quote inside of a string if you had to put a single quote inside of a single-quoted string or a double quote inside of a double-quoted string. Lastly, you can also move the cursor back one and cause a carriage return, which moves it to the beginning of the line.

04:57 These last two characters are useful for doing animation, which I’ll talk about in a later lesson.

05:05 Let’s look at some of these in action. I’m going to start by entering a string with some newlines and some tabs in it.

05:13 With each "\n" I get a new line of text, and with the "\t" I get a tab moving my text in by eight spaces. Let’s try some low-grade audio fun. Printing a "\a" makes a “bong” noise.

05:29 The sound you get will actually vary depending on your operating system, and in newer operating systems, you can actually set the sound that gets played. In old operating systems, this was just a little “boop” noise out of your speaker.

05:42 Text inside of your computer is represented in an encoding. One of the older encodings that is common through most computers is something called ASCII. For example, capital letter 'A' in 'ASCII' is the number 65.

05:55 You can represent numbers in decimal, octal, and hexadecimal notations, and in print(), you can use that to print out special characters. So octal 275, which is decimal 189, is ½, or at least it is in the font I’m using.

06:12 It varies depending on what your encodings are. I can now do the same thing using hex. 275 hex is BD and I get the same character.

06:27 How about some embedded quotes? I can escape a \" or a \' so that I can put quotes inside of my quotes no matter how I’ve created strings. The backslash ( \ ) character is how you formulate an escape sequence. So, what if you only want a backslash?

06:43 Well, backslash backslash ( \\ ) gives you a single backslash ( \ ).

06:49 Easy enough. Now, something a little trickier. How about the carriage return? \r puts the cursor back to the beginning of the line. This can cause some weirdnesses. Notice that what gets printed here is only part of our string. "Carriage return means go back \r", then the cursor goes to the beginning of the line and starts overwriting with "to the start of the line".

07:15 Because "to the start of the line" is shorter than the first segment, you still get the word "back" trailing at the remainder.

07:23 This is a little messy, but it’s actually useful when you do animation, which I will talk about in a later lesson.

07:31 There are certain kinds of strings where backslashes are common. Windows file paths and regular expressions frequently use them. This makes putting backslash backslash ( \\ ) inside of your strings on all the backslashes kind of messy. You can get some pretty ugly strings pretty quickly.

07:48 Python provides a way to get around this, and that’s the raw string. You prefix an r in front of the string and everything inside of it will ignore escape characters.

07:57 This allows you to have a lot of cleaner-to-read strings in the case where you have a lot of backslashes.

08:03 One final trick that I like to use is you can multiply strings to tell Python to repeat them. 70 * '='? 70 =’s! I like this because it gives me a nice little divider I can put on the output.

08:17 Simple things amuse me. In the next lesson, I’ll be talking about the different ways to format strings in Python.

Sumanyu on Aug. 1, 2020

Hi,

I run python 3 on IDLE and the Ascii Bell (\a) doesn’t work.

Sumanyu on Aug. 1, 2020

carriage return also doesn’t work

Christopher Trudeau RP Team on Aug. 1, 2020

Yep, looks like you’re right. IDLE isn’t an operating system shell, it is built as a cross platform REPL based on tkinter. It looks like tkinter doesn’t pass everything down to the operating system and doesn’t fully emulate a terminal.

I tested it on macOS and the bell did nothing. The \r does something, but not what I would consider the “normal” thing – on my system it feeds two lines, instead of just acting as a line feed in the same place.

It also isn’t hooked into some of the normal macOS keyboard mechanisms. I can’t, for example, pop up the character selection menu that makes it easy to type unicode or emjoii.

If you want to play with these things, I would suggest running the code directly in a terminal.

Sumanyu on Aug. 1, 2020

Ok. Thanks! Means we can do nothing to run these commands on IDLE?

Christopher Trudeau RP Team on Aug. 2, 2020

I’ve not used IDLE before. My guess is “no” from what I can see of it, but someone who knows better might know a hack.

Everything you do with print() is dependent on the underlying terminal that is displaying the result. You can also get some weirdnesses happening when you are remotely logged into a machine because the terminal emulation across the connection translates the strings differently.

Sumanyu on Aug. 3, 2020

Ok, thanks!

Become a Member to join the conversation.