Python Tutorial: String Formatting - Advanced Operations for Dicts, Lists, Numbers, and Dates

Corey Schafer · Beginner ·🛠️ AI Tools & Apps ·10y ago

Key Takeaways

This video tutorial by Corey Schafer covers advanced string formatting operations in Python, including formatting for dictionaries, lists, numbers, and dates using the format() method and various format specifiers.

Full Transcript

Hey everybody, how's it going? In this video, we're going to be looking at string formatting operations in Python. Now, a lot of people know the basics of string formatting, but there are a lot of options beyond the basics that are available that will allow us to format our strings in exactly the way that we want. So, I'm going to run through a few examples here really fast just to show some of the different things that we can do with formatting our strings. So, first of all, if you're not already using some kind of formatting when you print out your strings, then you definitely should be. So sometimes I'll see people using string concatenation to display information and that's exactly what I'm doing on this first line here. And there are a few things wrong with this. So you can see first of all it's not very readable. You have to open and close strings in different places. Uh plus you have plus signs everywhere. Uh whenever you have an integer you have to cast those to strings. And also you have to remember to put spaces in the correct location. So this uh middle string here, I have to remember to put in a space at the beginning and at the end. And if I mess that up, then it can bunch my string together when I print it out. So you can see if I run this code that it does work, but there are much better ways to do this. So uh it's much easier to use the formatting option, and that's what we're going to take a look at here. So let me uncomment out this so you can see that this is a lot easier to read. Now we have these braces here as placeholders and after our string closes we run this format method and then we pass in the values that we want to replace our placeholders with. Now if we do it the way that I did here and don't add anything to these placeholders, then what it's going to do is it's just going to pass our first value here to our first placeholder and our second value to our second placeholder. Now, if you want to, you can explicitly number your placeholders. So, in this example here, it's the exact same example, but now I've numbered my placeholders. So, now what this is saying is that we want this zero here is the first value that you pass in format, and then this one is the second value that you pass in the format. And if I save that and run it, you can see that it still works. Now, this is more useful when you have placeholders for values that need to be repeated. So in this next example that I have here, uh you can see that I have this tag variable and this text variable. So in my string, I'm putting the tag in some opening brackets here. And then I'm putting in a placeholder for the text. And then I'm putting the tag inside these closing braces here. And then the values that I pass into format tag will go where all of the zeros are for our placeholders and text will go where the one is for our placeholder. So if I save that and run it, you can see that it prints out the value that we expected. Okay. So now we can also grab specific fields from our placeholders. So in our previous example, we were passing in a dictionary to our format and within our format, we were accessing the name and the age uh of this dictionary from directly within the format here. But we can actually access these fields from directly within the placeholders. So within the placeholder here for zero, I'm just going to put these brackets here and do name. And for one, I'm going to do age. And then I can take these off of our dictionary here and just pass in the dictionary. So let me save that and run it. And you can see that that still works. Now another thing that you might notice is that now you can see that I'm just passing in this dictionary into format twice. I have person and person. So really what I can do is I can just make both of these a zero index to take the first value from format and then I can get rid of the second value. And now what this is going to do is it's going to pass the person dictionary to all of our placeholders. And here it's going to access the name and here it's going to access the age. So if I save that and run it then you can see that it still works. Now this is also how you would access values of a list too. So, for example, let me do uh L equals and make a list here. And I'm just going to do the exact same value. So, I'm going to do gen and 23. And here I'm going to pass in that list. And now instead of name, I'm going to grab the first index there and then the next index and save that and run it. And you can see that that works also. Okay. So, that is how you access values from dictionaries and lists. But you can also access attributes in a similar way. Okay. So I have a small test class here called person. And this has a name attribute and an age attribute. And then here I'm uh making an instance of this class person with the name Jack and the age 33. Now, if I want to print this out, it's almost the same as what we did with the dictionary, but now instead of using the brackets, we're just going to use this attribute to grab that value. So, you can see here I'm still just passing in this single object into format and it's going to come in here and grab the name attribute and the age attribute. So, if I save that and run it, you can see that that worked. Okay. So we can also pass in keyword arguments to format. So for my example that I have here, uh I have my placeholders and I'm just passing in some keywords into the placeholders. Now within format here, instead of passing in a specific object, I'm setting these keyword values. So I'm setting name equal to Jin and the age equal to 23. So now anywhere that it sees a placeholder that matches that keyword then it'll fill it in with that value. So if I save that and run it then you can see that that worked right. Now this is the method that I usually use to print out uh dictionaries because I think that it is a little bit more readable. Now, if you know about unpacking lists and dictionaries, then you'll probably realize here that we can just unpack our dictionary from before into format, and it will find all those keywords for us to use. So, I actually accidentally deleted that dictionary that we had from before. Uh, so let me go ahead and make that again. So, let's see, that was name, and I'll just do Jen, and I'll do the age as 23. And let me fix that curly brace there. Okay. So now in this example here, I'm using these keyword arguments. And if I just unpack that dictionary, then it will fill in those keyword arguments for us. So let me save that and print it. And you can see that that worked. So uh to me, that's the most readable and most convenient way to print out dictionary values. Okay. So now let's take a look at how we can format and print out numbers. So in this example that I have here, all I'm doing here is looping through and printing out the numbers 1 through 10. So now, what if I wanted all of these numbers to have two digits and zero pad my singledigit values uh with a zero? Now, in order to do this, I'm going to have to add formatting to our placeholders. And we can do that by adding a colon here. So now we can add whatever formatting that we'd like. So I want to zero pad my digits to two. So we can do that just by doing a 02 here. And if I save that and run it now you can see instead of 1 2 3 it's 0 1 02. And then when I get down here to 10, it doesn't pad it because it's already two digits. Now if I was to make this a three and save that and run it. Now you can see that it zero pads all the way up to three digits. Okay. So now let's look at using format to do uh decimal places. So here I have pi written out to eight decimal places. So let's say that I want to print that out, but I only want to print out uh to two decimal places. So let me add my colon so that it knows that we want to do some formatting. And now I can specify that I want two decimal places just by doing a 2F. So now if I save that and run it, you can see that it says pi is equal to 3.14. And again, if I change that two to a three and save it and run it, and it does up to three decimal places. Okay, so let's look at an example for uh say that we wanted to print out a large number and we wanted some comma separators so that it was more re um more easily readable. So we can easily do that just by adding a comma after our colon. So I'll do a colon here to specify that we want formatting. Then I'll just put in a comma. And if I save that and run it, you can see that we have our comma separators here on these large values. And you can chain this formatting together too. So let's say that we wanted the commaepparated values and we wanted to display up to two decimal places. So I right after the comma I could do my 2F that we did from before and if I run that you can see that we have our comma separated values and it added two decimal places onto the end. Okay. So let's take a look at an example for how we can format and print out dates. So I think this is extremely useful if you need to uh print out datetime information. It allows us to display the information in just about any way that we want. So, it's especially useful if you're printing out dates for logs or creating reports or anything like that. So, I just created a date here for September 24th of 2016. So, if I just print out that date variable, then you can see that it's not too bad. It's pretty easy to tell what it's doing. It's printing out the year, the month, the day, and then the hours, minutes, and seconds. But let's say that we wanted it in this format here. We wanted the month, the day, and then a comma and the year. So, let's take out this print statement here, and let's try to do that. Okay. So, first of all, we're going to want to add our colon here to specify that we want to do some formatting to this. And now, I'm going to go to the website and get the values that we want to use here. So, we want the full month. And we can see here that the full month is percent sign B. And we also want the day of the month. And we can see that the day of the month here is percent sign D. And we also want the year here. And there's a couple of options for the year. Uh but we're going to go ahead and just do the four-digit one here with the capital Y. So, like I said, it's completely fine if you don't know these formatting options. Just whenever you're trying to do something, you can look it up in the documentation and know how to get it done. So let's go ahead and pass these in. So the name of the month was a percent sign B and then I'm going to do the day is percent sign D and then I want the comma and then the percent sign capital Y for the year. So let me go ahead and print that out. Okay, so that worked the way that we wanted it to. So you can see how formatting your strings like this uh could be extremely useful for printing out dates. So now let's do a slightly more complicated example and let's try to do it in this format here. Let's say that we want the name of the month, the day, the comma, the year. Then we want to say that it fell on a and then put in the day of the week and that it was the uh day of the year. So I want to put the day of the year here. So we want to format our string to where it looks like this. So let me uncomment out what we have here so far. Now, we already know how to do this first part here. So, that was just a comm uh colon, and we want our percent sign D, percent sign D for the day, comma, percent sign, capital Y. So, now let's also go back to the documentation and find the day of the week and the day of the year. So, I'm going to go and grab that. So we can see here that the day of the week is over here at capital A and the day of the year is this percent sign J. So if I go back here and do our colon and a percent sign with a capital A and then over here I'm going to do the colon with percent sign lowercase J. Now if I just try to run this as is then you can see that we get an error. Now, the reason that we got an error is because we have three placeholders, but we're only passing in one value to our format. So, if you remember, I can just do the index here. So, I can say that we want this to be the zero index and the first value that we pass into format. So, now even though we have three placeholders, it will replace all of those placeholders with our single value that we're passing in to format. So now if I run that, you can see that it gives us the output that we wanted. So now you can see here that it says September 24th, 2016 fell on a Saturday and was the 268th day of the year. So I think that's going to do it for this video. I hope it helped in knowing what all is available when it comes to string formatting and also maybe gave you some ideas for how you can use this in your own applications. Uh but if you do have any questions, just feel free to ask me in the comment section below. Uh, be sure to subscribe for future videos and thank you all for watching.

Original Description

In this Python tutorial, we will be learning how to perform some advanced string formatting operations. Formatting our strings allows us to display our information in exactly the way we would like it to be displayed. Everyone, in almost all areas of Python programming, comes across a situation where they need to format a data type in a specific way. Let's get started. The code from this video can be found at: https://github.com/CoreyMSchafer/code_snippets/tree/master/String-Formatting ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Corey Schafer · Corey Schafer · 0 of 60

← Previous Next →
1 Web fonts using CSS Font Face
Web fonts using CSS Font Face
Corey Schafer
2 Using Font Awesome in Desktop Applications (OS X)
Using Font Awesome in Desktop Applications (OS X)
Corey Schafer
3 Sublime Text 2: Setup, Package Control, and Settings
Sublime Text 2: Setup, Package Control, and Settings
Corey Schafer
4 ArcGIS API for JavaScript Part 1: Our First Web Map
ArcGIS API for JavaScript Part 1: Our First Web Map
Corey Schafer
5 Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Corey Schafer
6 Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Corey Schafer
7 ArcGIS API for JavaScript Part 2: Starting Templates
ArcGIS API for JavaScript Part 2: Starting Templates
Corey Schafer
8 Paver Patio Time Lapse
Paver Patio Time Lapse
Corey Schafer
9 Mac Tip: Ways to perform Screen Capturing and Screenshots
Mac Tip: Ways to perform Screen Capturing and Screenshots
Corey Schafer
10 WordPress Plugins: Imsanity
WordPress Plugins: Imsanity
Corey Schafer
11 WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
Corey Schafer
12 Sublime Text 3: Setup, Package Control, and Settings
Sublime Text 3: Setup, Package Control, and Settings
Corey Schafer
13 Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Corey Schafer
14 Mac Tip: Adding Folder Stacks to the Dock
Mac Tip: Adding Folder Stacks to the Dock
Corey Schafer
15 CSS Tips and Tricks: Add External URLs to Print Stylesheets
CSS Tips and Tricks: Add External URLs to Print Stylesheets
Corey Schafer
16 JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
Corey Schafer
17 JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
Corey Schafer
18 JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
Corey Schafer
19 JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
Corey Schafer
20 JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
Corey Schafer
21 JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
Corey Schafer
22 JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
Corey Schafer
23 Python Tutorial: if __name__ == '__main__'
Python Tutorial: if __name__ == '__main__'
Corey Schafer
24 Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Corey Schafer
25 How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
Corey Schafer
26 Easily Resize Multiple Images Using Picasa
Easily Resize Multiple Images Using Picasa
Corey Schafer
27 Easily Resize Multiple Images Using the Mac Terminal
Easily Resize Multiple Images Using the Mac Terminal
Corey Schafer
28 Python Tutorial: virtualenv and why you should use virtual environments
Python Tutorial: virtualenv and why you should use virtual environments
Corey Schafer
29 Python Tutorial: pip - An in-depth look at the package management system
Python Tutorial: pip - An in-depth look at the package management system
Corey Schafer
30 Git Tutorial: Using the Stash Command
Git Tutorial: Using the Stash Command
Corey Schafer
31 How Software Engineers, Developers, and Designers can volunteer their skills
How Software Engineers, Developers, and Designers can volunteer their skills
Corey Schafer
32 Git Tutorial: Diff and Merge Tools
Git Tutorial: Diff and Merge Tools
Corey Schafer
33 Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Corey Schafer
34 Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Corey Schafer
35 Python Tutorial: str() vs repr()
Python Tutorial: str() vs repr()
Corey Schafer
36 Programming Terms: DRY (Don't Repeat Yourself)
Programming Terms: DRY (Don't Repeat Yourself)
Corey Schafer
37 Programming Terms: String Interpolation
Programming Terms: String Interpolation
Corey Schafer
38 Programming Terms: Idempotence
Programming Terms: Idempotence
Corey Schafer
39 Python Tutorial: Namedtuple - When and why should you use namedtuples?
Python Tutorial: Namedtuple - When and why should you use namedtuples?
Corey Schafer
40 Programming Terms: Mutable vs Immutable
Programming Terms: Mutable vs Immutable
Corey Schafer
41 Python Tutorial: Else Clauses on Loops
Python Tutorial: Else Clauses on Loops
Corey Schafer
42 Overview of Online Learning Resources
Overview of Online Learning Resources
Corey Schafer
43 Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Corey Schafer
44 Git Tutorial for Beginners: Command-Line Fundamentals
Git Tutorial for Beginners: Command-Line Fundamentals
Corey Schafer
45 Quickest and Easiest Way to Run a Local Web-Server
Quickest and Easiest Way to Run a Local Web-Server
Corey Schafer
46 Python Tutorial: Generators - How to use them and the benefits you receive
Python Tutorial: Generators - How to use them and the benefits you receive
Corey Schafer
47 Python Tutorial: Comprehensions - How they work and why you should be using them
Python Tutorial: Comprehensions - How they work and why you should be using them
Corey Schafer
48 Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Corey Schafer
49 Programming Terms: Combinations and Permutations
Programming Terms: Combinations and Permutations
Corey Schafer
50 Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Corey Schafer
51 Preparing for a Python Interview: 10 Things You Should Know
Preparing for a Python Interview: 10 Things You Should Know
Corey Schafer
52 SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
Corey Schafer
53 SQL Tutorial for Beginners 2: Creating Your First Table
SQL Tutorial for Beginners 2: Creating Your First Table
Corey Schafer
54 SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
Corey Schafer
55 Linux/Mac Terminal Tutorial: Navigating your Filesystem
Linux/Mac Terminal Tutorial: Navigating your Filesystem
Corey Schafer
56 Python: Ex Machina Easter Egg - Hidden Message within the Code
Python: Ex Machina Easter Egg - Hidden Message within the Code
Corey Schafer
57 Mac Tip: New Split Screen Feature in El Capitan
Mac Tip: New Split Screen Feature in El Capitan
Corey Schafer
58 Setting up a Python Development Environment in Eclipse
Setting up a Python Development Environment in Eclipse
Corey Schafer
59 Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Corey Schafer
60 SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
Corey Schafer

This tutorial teaches advanced string formatting operations in Python, including how to format dictionaries, lists, numbers, and dates. It covers various format specifiers and how to use the format() method to achieve desired output.

Key Takeaways
  1. Run through examples of string formatting operations
  2. Use format() to replace placeholders with values
  3. Access specific fields from dictionary within placeholders
  4. Use format() to pad numbers with zeros
  5. Specify decimal places and comma separators
  6. Format dates using format specifiers like %B, %D, %Y
  7. Use chained format specifiers to format multiple parts of a string
💡 The format() method in Python can handle multiple placeholders with different types, making it a powerful tool for advanced string formatting operations.

Related AI Lessons

Up next
Salesforce Flow New Features (Summer '26) | Open Record, URL & Show Toast Messages
AITECHONE
Watch →