Python String Formatting: Overview
An overview of what you’ll learn in this course. You’ll see reasons why strings need formatting and the four different string formatting methods that Python supports.
00:01
Hi there! In this video, we’re going to talk about the four major ways of string formatting in Python and best practices for each. The four ways are string formatting with the modulo or interpolation operator (%
), string formatting with the .format()
or format method, f-strings, and last but not least, template strings. We’ll also cover which method you should use. So, let’s talk about some reasons.
00:29 What are some reasons we should format strings? We can use them to organize data with rows, columns, whitespace padding. We can set up logging and use variables to concatenate or join together strings that make for verbose logs that are very helpful. Similarly, we can use them for printing errors onscreen and we can use them to give us some sort of feedback while our program’s running. Those are just a few reasons.
00:55 You’ll probably find a lot of reasons during your Python career to use string formatting. But in a nutshell, the reason we want to format strings is to provide some sort of readable, human-or computer-usable output from our program. That being said, let’s jump into coding and some examples.
01:11 The first thing we’ll do is set up our scenario. So here I am in the console, you should open yours up and follow along with me. We’re going to have a few great scenarios to get you used to string formatting.
01:23
The first thing we’re going to do is initialize two variables. The first one, errno
, for error number, 50159747054
. The second is going to be a name. We’ll give it 'Bob'
.
01:40 Now, what we want to do with these two variables is substitute them into a string that’s going to look something like this.
01:51
'Hey name there is an errno error!'
.
01:58
So we want that to print out but where we have 'name'
and 'errno'
, we want our strings to substitute the name 'Bob'
and our integer.
Become a Member to join the conversation.