Hướng dẫn print f python
As of Python 3.6, f-strings are a great new way to format strings. Not only are they more readable, more concise, and less prone to error than other ways of formatting, but they are also faster! Show
Nội dung chính
Nội dung chính
By the end of this article, you will learn how and why to start using f-strings today. But first, here’s what life was like before f-strings, back when you had to walk to school uphill both ways in the snow. “Old-school” String Formatting in PythonBefore Python 3.6, you had two main ways of embedding Python expressions inside string literals for formatting:
%-formatting and Option #1: %-formattingThis is the OG of Python formatting and has been in the language since the very beginning. You can read more in the Python docs. Keep in mind that %-formatting is not recommended by the docs, which contain the following note:
How to Use %-formattingString objects have a built-in operation using the >>>
In order to insert more than one variable, you must use a tuple of those variables. Here’s how you would do that: >>>
Why %-formatting Isn’t GreatThe code examples that you just saw above are readable enough. However, once you start using several parameters and longer strings, your code will quickly become much less easily readable. Things are starting to look a little messy already: >>>
Unfortunately, this kind of formatting isn’t great because it is verbose and leads to errors, like not displaying tuples or dictionaries correctly. Fortunately, there are brighter days ahead. Option #2: str.format()This newer way of getting the job done was introduced in Python 2.6. You can check out A Guide to the Newer Python String Format Techniques for more info. How To Use str.format()
With >>>
You can reference variables in any order by referencing their index: >>>
But if you insert the variable names, you get the added perk of being able to pass objects and then reference parameters and methods in between the braces: >>>
You can also use >>>
Why str.format() Isn’t GreatCode using >>>
If you had the variables you wanted to pass to f-Strings: A New and Improved Way to Format Strings in PythonThe good news is that f-strings are here to save the day. They slice! They dice! They make julienne fries! Okay, they do none of those things, but they do make formatting easier. They joined the party in Python 3.6. You can read all about it in PEP 498, which was written by Eric V. Smith in August of 2015. Also called “formatted string literals,” f-strings
are string literals that have an Here are some of the ways f-strings can make your life easier. Simple SyntaxThe syntax is similar to the one you used with >>>
It would also be valid to use a capital letter >>>
Do you love f-strings yet? I hope that, by the end of this article, you’ll answer Arbitrary ExpressionsBecause f-strings are evaluated at runtime, you can put any and all valid Python expressions in them. This allows you to do some nifty things. You could do something pretty straightforward, like this: But you could also call functions. Here’s an example: >>>
You also have the option of calling a method directly: >>>
You could even use objects created from classes with f-strings. Imagine you had the following class:
You’d be able to do this: >>>
The The string returned by By default, f-strings will use >>>
If you’d like to read some of the conversation that resulted in f-strings supporting full Python expressions, you can do so here. Multiline f-StringsYou can have multiline strings: >>>
But
remember that you need to place an >>>
If you don’t put an If you want to spread strings over multiple lines, you also have the option of escaping a return with a >>>
But this is
what will happen if you use >>>
Read up on indentation guidelines in PEP 8. SpeedThe f-strings are faster than both %-formatting and
At runtime, the expression inside the curly braces is evaluated in its own scope and then put together with the string literal part of the f-string. The resulting string is then returned. That’s all it takes. Here’s a speed comparison: >>>
>>>
>>>
As you can see, f-strings come out on top. However, that wasn’t always the case. When they were first implemented, they had some speed issues and needed to be made faster than Python f-Strings: The Pesky DetailsNow that you’ve learned all about why f-strings are great, I’m sure you want to get out there and start using them. Here are a few details to keep in mind as you venture off into this brave new world. Quotation MarksYou can use various types of quotation marks inside the expressions. Just make sure you are not using the same type of quotation mark on the outside of the f-string as you are using in the expression. This code will work: >>>
This code will also work: >>>
You can also use triple quotes: >>>
>>>
If you find you need to use the same type of quotation mark on both the inside and the outside of the string, then you can escape with >>>
DictionariesSpeaking of quotation marks, watch out when you are working with dictionaries. If you are going to use single quotation marks for the keys of the dictionary, then remember to make sure you’re using double quotation marks for the f-strings containing the keys. This will work: >>>
But this will be a hot mess with a syntax error: >>>
If you use the same type of quotation mark around the dictionary keys as you do on the outside of the f-string, then the quotation mark at the beginning of the first dictionary key will be interpreted as the end of the string. BracesIn order to make a brace appear in your string, you must use double braces: >>>
Note that using triple braces will result in there being only single braces in your string: >>>
However, you can get more braces to show if you use more than triple braces: >>>
BackslashesAs you saw earlier, it is possible for you to use backslash escapes in the string portion of an f-string. However, you can’t use backslashes to escape in the expression part of an f-string: >>>
You can work around this by evaluating the expression beforehand and using the result in the f-string: >>>
Go Forth and Format!You can still use the older ways of formatting strings, but with f-strings, you now have a more concise, readable, and convenient way that is both faster and less prone to error. Simplifying your life by using f-strings is a great reason to start using Python 3.6 if you haven’t already made the switch. (If you are still using Python 2, don’t forget that 2020 will be here soon!) According to the Zen of Python, when you need to decide how to do something, then “[t]here should be one– and preferably only one –obvious way to do it.” Although f-strings aren’t the only possible way for you to format strings, they are in a great position to become that one obvious way to get the job done. Further ReadingIf you’d like to read an extended discussion about string interpolation, take a look at PEP 502. Also, the PEP 536 draft has some more thoughts about the future of f-strings. For more fun with strings, check out the following articles:
Happy Pythoning! |