Python Quick Tip: F-Strings - How to Use Them and Advanced String Formatting

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

Key Takeaways

This video tutorial demonstrates the use of f-strings in Python 3.6 and above for string formatting, including advanced techniques such as accessing dictionary values, performing calculations, and customizing output with date/time formatting codes. The tutorial covers the basics of f-strings, including how to use them to format strings, and provides examples of how to use f-strings to print out complex data structures.

Full Transcript

hey there how's it going everybody now this is going to be a quick video where I show you a feature that you've likely seen me use and a lot of my videos so far and that is F string so f strings are a new way to format strings in Python 3.6 and above and I prefer using them over any other formatting methods so if you're not using Python 3.6 or higher then you'll need to install that in order to follow along with this video okay so let's take a couple of examples and see why I prefer using these so first of all I have two variables here at the top so I have first name and last name so let's say that I wanted to print a sentence that says my name is and then include the first name and last name in that string now the way you've probably been familiar with doing this is with the format method and this is how I used to do it too as well so we have our curly braces here as placeholders and then we're using our format method to feel in the placeholders with these values so the first name is going to put get put in the first placeholder here and the last name is going to get put in the second place holder here now if any of this is unfamiliar to you then I do have an older video where I go in-depth on how to use the format method that goes over a lot of these same examples that I'm going to use in this video with F strings so if you're curious then you can watch that first okay so this should work how I have it right now with this format method so if I save this and run it then you can see that we did get our sentence with our values that we wanted but right now this is not extremely elegant or intuitive so for example if we have a lot of placeholders then we kind of have to go back and forth to see what placeholders match up with what values so I'd have to go back and forth between the format method here and the placeholder to see where what is going to get filled in where but now let's see what this looks like using an F string so I'm going to comment out what we have here and I'm going to uncomment out the section here and I'll bring this up one so so far here I have a sentence that has our two placeholders and I've removed the format method now instead we're simply going to use an F string and to specify that we want this to be an F string then we just put an F in front of the string here to tell Python that this is going to be an F string a formatted string and now instead of using the format method we can simply add our variables directly into our placeholders so within the curly braces here I'm going to say first name and within the second one here I'm going to say last name so if I save this and run it then you can see that we get the same result and that this works but also look at how much more intuitive this looks we no longer have to go back and forth between our placeholders and the format method to see what will be added where we can just look at this directly and see that our string will be equal to my name is and then our first name and then followed by space and then our last name now another cool thing is that we can actually run functions or methods directly within the EPS string so let's say that we wanted our first and last name to be capitalized so to do that we could simply come in here and say first name dot upper and also say last name dot upper and if I save that and run it that you can see then our output it says my name is and then it capitalized our first name and last name so I personally think that that's extremely simple and a lot easier to read than if these were in a format method okay so let's take a look at how we would print out some dictionary values using an F string so I'm going to remove all of this and uncomment out this section here so I have a dictionary here and the dictionary just has a key of name with a value of gin and a key of age with a value of 23 and now I have another sentence here where we have a couple of placeholders and I'm using a format method for now and to the first placeholder we're passing in this person and accessing that name key which should be gin and the second value here we are putting the person and accessing that h key which should be 23 so this sentence should say my name is Jen and I am 23 years old so this is how we would do this with the format method so if I save this and run it then you can see that that works fine but now let's see how we do this with an F string so I'm going to comment out that and uncomment out our second part here so we have our string with our placeholders and we also have our F at the beginning to specify that this is an F string now there is one thing that we need to watch out for here now since we are now going to access the keys directly within the string we now have to figure out what to do with the quotes we're using to access that key so let me show you what I mean so if I try to just put this in directly into our placeholder like we did before so I'll say person and access our name and then also person and access the age then our single quotes that we're using here to access our key to our dictionary is terminating our string early because we opened our string with a single quote as well so if I run this then it should give me a syntax error and it does it says invalid syntax so to avoid this if you're using single quotes inside of your F string then simply use double quotes to open and close your string then the single quotes will no longer conflict with those and I do this with normal strings as well I'd rather change the quotes than look at a bunch of escape sequences and stuff like that so let me change the opening and closing quotes so if I come in here I'll just open this with a double quote and I will close that with a double quote and now our single quotes are no longer affecting the opening or closing of our string so now if I save this and run it then you can see that that works fine okay so now let me show you a few other things that we can do before ending this video so let me uncomment out this line here so like I said we can run functions and methods from directly within the F string but we can also do calculations so in this example I and simply go into our placeholder so our string says four times eleven is equal to and I can simply go in our placeholder and say four times eleven and then I can save that and run it and we can see that within our F string it did that calculation so it says four times eleven is equal to forty four now we can also do some more advanced formatting and our F strings as well so in this next example let me uncomment out this in this example I am looping through a range of values of one through ten and I am just printing those out through each loop so I'm printing out the value of n each time we go through the loop so if I save this and run it then we can see that our result is the value is 1 by use 2 and so on but let's say that I wanted each of these values to be 0 padded by a certain amount so sometimes it can be important to 0 pad values when adding them to a database or to expect a certain length or anything like that so to do this we can go up into our F string here and just put a colon after our value to specify that we're going to do some additional formatting and now if we wanted to 0 pad by 2 digits then we can simply say 0 to specify 0 padding and then 2 for 2 digits so if I save that and run it then now we can see in our loop here that all of our values have a leading 0 except for the 10 because it's already two digits so if we wanted to 0 pad by 3 or 4 digits or whatever then you can simply change this 2 to whatever you'd like so if I change that to a 4 save it and run it you can see that now we are Z 0 padded with four digits total okay so now let's move on to floating point values so let me get rid of that and oncome and uncomment this section here okay so here I have pi written out to a certain number of values and in our string we are simply printing that out so we have an F string here that says pi is equal to and then just printing out pi so if I save that and run it then we can see that that works but what if that is a longer floating point number than what we want to print so let's say that we want to print two four digits than to do this we can put a colon after our value here and the place holder like we did before to specify that we're going to do some extra formatting and now we to specify that we want to only print up to four digits then we can say point here a dot to specify a floating point and then I'll say four four four digits and then an F for a floating point value so I'll save that and run it and you can see that now we have a precision of four that we're printing out this value and we can see that it also rounded this up correctly so it's not just chopping that value off and again if you'd like to change the precision then you can simply change that forward to any value that you'd like so if I do five save that and run it then you can see that now it's five digit precision there okay so lastly let's take a quick look at formatting and printing dates so I'll get rid of that there and come down here and uncomment out this section and I'll separate out the import statement there now this is probably the kind of formatting that I use most often because the way that we want to display dates can vary so much okay so I have created a date time here that is a fake birthday of January 1st 1990 and we can see that we're currently just passing this date time directly into our placeholder in our F string and printing that out so let's see what that looks like by default so if I save this and run it then we can see that it says jen has a birthday on 1991 one and then the minutes and seconds there so we can see that that's not the best-looking output now we can read it but it would be nice if we could change this to whatever we'd like so let's say that I wanted to this to literally output you know Jen has a birthday on January 1st 1990 now to do this we're gonna have to know the date/time formatting codes and I never remember these I'm constantly needing to look them up but if we go to our site here this is just the Python documentation here in section eight point one point eight towards it's basically towards the bottom of the date-time documentation and this will give you the codes for whatever output you want so for example we can see that the percent sign uppercase B here is the code for the entire month spelled out and it gives some examples here and the lowercase B here is an abbreviated month so remember for our output I wanted it to say January 1st 1990 so what we're gonna want is this uppercase B to spell out January and then it looks like this lowercase D is the day and then for the year we want this capital Y to do a four-digit year this lowercase Y is just a two-digit year without the century so we're going to go with the uppercase Y so let's go back to our example and now let's fill in these values to format our string how we like so just like we've seen before I'm going to add a colon after our value to specify that we want to do some additional formatting here and now we can just type in how we want this to look using those codes that we solve from the documentation so I'm gonna say % b2 have the month first and then a space and then % D to give the day and then I'm going to do a comma after the day and then to do the year that's going to be % uppercase Y so now if I save this and run it then we can see that it says Jin has a birthday on January 1st comma 1990 so we can see that we got the formatting that we were hoping for and that that worked well ok so I think that is going to do it for this video hopefully now you have a good idea for how you can use f strings and if you see me using it in future videos then nothing will throw you off but if you do have any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoy these tutorials and would like to support them then there are several ways you can do that these dis ways to simply like the video and give it a thumbs up and also a huge help to share these videos with anyone who you think would find them useful and you have the means you can contribute through patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching you

Original Description

In this Python Programming Tutorial, we will be learning how to use f-strings to format strings. F-strings are new to Python3.6+ and are extremely useful once you learn how to use them. Viewers have likely seen me use f-strings in previous videos so this video will go into detail exactly how to use them so that everyone can follow along confidently. Let's get started... ✅ 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 video tutorial teaches how to use f-strings in Python for string formatting, including advanced techniques such as accessing dictionary values and customizing output with date/time formatting codes. The tutorial provides examples of how to use f-strings to print out complex data structures and covers the basics of f-strings, including how to use them to format strings.

Key Takeaways
  1. Comment out the format method
  2. Uncomment the F-string section
  3. Add variables directly into placeholders
  4. Run functions or methods directly within the F-string
  5. Access dictionary values directly
  6. Perform calculations within F-strings
  7. Use F-strings for 0 padding values
  8. Specify precision for floating point numbers
  9. Use date/time formatting codes to customize output
💡 F-strings provide a more intuitive and flexible way to format strings in Python compared to the format method, and can be used to access dictionary values, perform calculations, and customize output with date/time formatting codes.

Related Reads

📰
Stop Copying Meeting Details from Email to Calendar — Automate It with n8n and GPT-4o-mini
Automate copying meeting details from email to calendar using n8n and GPT-4o-mini, saving time and reducing errors
Dev.to · AgoraIntelligence
📰
I started using Claude AI and I only wanted to write an email
Discover 10 use cases for Claude AI beyond writing emails and unlock its full potential for productivity and automation
Medium · AI
📰
AI & Automation Tools: Zapier vs Make vs n8n (Real-World Test)
Learn how to automate workflows using Zapier, Make, and n8n, and discover which tool performs best in real-world tests
Dev.to AI
📰
How I Automated the Most Annoying Part of Building in Public
Automate the tedious parts of building in public to save time and focus on development
Dev.to · Portrait Pro by Videograph
Up next
RunMeet by Runable Review | AI Joins Meetings, Takes Notes & Builds Websites
SuccessPursuitZone
Watch →