Here are 73 examples. Thoroughly master the usage of f-string!

Keywords: Python

Original text: https://jishuin.proginn.com/p/763bfbd32655

In this article, I'll show you some of the techniques I think are most important for Python to format string f-string. You will learn a variety of ways to format strings through various examples. Overall, you'll see 73 examples of how to use f-string perfectly.

 

List of contents

 

1. What is f-string?

two   Basic text formatting with python

3. f-string   limitations

four   How to format expressions

five   How to use f-string to debug your code

six   How to format numbers in different base numbers

seven   How to print out objects using formatted string constants

eight   How to set floating point precision in a formatted string constant

nine   How to format numbers as percentages

ten   How to adjust or increase the padding of f-string

eleven   How to escape characters

twelve   How to center a string

thirteen   How to add thousands separator

13.1 how to format numbers using commas as thousands separator

13.2 how to format numbers using commas as decimal separators

14. How to format numbers with scientific counting (exponential counting)

15. In   f-string   Used in   if-else

16. How to use dictionary in f-string

17. How to use f-string   Splice string

18. How to format datetime   object

19. How to correct f-string   Invalid syntax error for

20. How to fill zero before a string

21. How to write multi line formatted string constants (how to deal with new line symbols)

22. Summary

 

1. What is an f-string in python?

 

In the history of python, string formatting has a long history. Before python 2.6, if you wanted to format a string, you could only use  % This placeholder, or string.Template module. Soon after, more flexible and reliable string formatting methods emerged:   str.format method.

 

% used in the past   Code example for string formatting:

>>> msg = 'hello world'>>> 'msg: %s' % msg'msg: hello world'

 

An example of using string.format:

>>> msg = 'hello world'>>> 'msg: {}'.format(msg)'msg: hello world'

 

To further simplify the formatting method, Eric Smith   Submitted in 2015   PEP 498 -- Literal String Interpolation   Proposal.

 

PEP 498 proposes a new string interpolation method, which can use str.format method more simply and conveniently. You just need to add a letter f at the beginning of the string to form the format of "f".

 

Example of using f-string:

>>> msg = 'hello world'>>> f'msg: {msg}''msg: hello world'

 

That's it! You no longer need to use string.format or%. However, f-string does not completely replace str.format. This article will also list the cases where the two are not common.

 

2. Basic string formatting

 

As mentioned above, formatting a string using f-string is simple. The only requirement is to give it a valid expression. F-string can also start with an uppercase f or be used in conjunction with r the original string. But you can't associate it with "b" or  ” u”   Mix.

 

>>> book = "The dog guide">>> num_pages = 124>>> f"The book {book} has{num_pages} pages"'The book The dog guide has 124 pages'
>>> F"The book {book} has{num_pages} pages"'The book The dog guide has 124 pages'>>> print(Fr"The book {book} has{num_pages} pages\n")
The book The dog guide has 124 pages\n >>> print(FR"The book {book} has{num_pages} pages\n")The book The dog guide has 124 pages\n>>> print(f"The book {book} has{num_pages} pages\n")The book The dog guide has 124 pages

 

That's about it! In the next section, I'll show you some examples of what you can or can't do with f-string.

 

3. Restriction of f-string

 

Although f-string is very convenient, it can not completely replace str.format. F-string evaluates in the context in which the expression appears. According to PEP498, this means that the expression can get all local and global variables. And the expression is an expression evaluated at run time. If in   {  }  If the expression used in cannot be evaluated, the following exception will pop up.

>>> f"{name}"---------------------------------------------------------------------------NameError                                 Traceback(most recent call last)<ipython-input-1in<module>----> 1 f"{name}"NameError: name 'name' is not defined

This is not a problem for str.format. You can define a template string in advance, and then pass context information when you invoke the.Format method.

>>> s = "{name}">>> s.format(name="Python")'Python'>>> print(s){name}

 

Another limitation is that you cannot use inline comments in f-string s.

>>> f"My name is {name #name}!"  File "", line 1    f"My name is {name #name}!"    ^SyntaxError: f-string expression part cannot include '#'

 

4. How to format an expression

 

If you don't want to define variables, you can use constants in braces. Python evaluates the expression and displays the final result.

>>> f"4 * 4 is {4 * 4}"'4 * 4 is 16'

Or you can

>>> n = 4
>>> f"4 * 4 is {n * n}"'4 * 4 is 16'

 

5. How to use   f-string   To debug the code

 

Debugging is one of the most common uses of f-string. Before Python 3.8, many people used a very complicated hello=42; F "Hello = {Hello}" to debug. A new feature has been introduced for Python 3.8. You can use f"{hello =}“   Rewrite the above code, and python will display hello=42. The following example shows how to apply this feature when using function expressions. The principle is the same as the above code.

>>> def magic_number():     ...:     return 42     ...: 
>>> f"{magic_number() = }"'magic_number() = 42'

6. How to format different base numbers

 

f-string can also display numbers in different base numbers. For example, you don't need to format an int through b to display its binary results.

>>> f'{7:b}''111'

To sum up, you can use f-string to format:

 

•    int   To binary

•    int   To hex

•    int   To octal

•    int   To hexadecimal (all symbols are capitalized)

 

The following example uses the indent function and hexadecimal formatting to create a table that can display the values of numbers in different hexadecimals.

>>> bases = {       "b": "bin",        "o": "oct",        "x": "hex",        "X": "HEX",        "d": "decimal"}>>> for n in range(1, 21):     ...:     for base, desc in bases.items():     ...:         print(f"{n:5{base}}", end=' ')     ...:     print()
1 1 1 1 1 10 2 2 2 2 11 3 3 3 3 100 4 4 4 4 101 5 5 5 5 110 6 6 6 6 111 7 7 7 7 1000 10 8 8 8 1001 11 9 9 9 1010 12 a A 10 1011 13 b B 11 1100 14 c C 12 1101 15 d D 13 1110 16 e E 14 1111 17 f F 15 10000 20 10 10 16 10001 21 11 11 17 10010 22 12 12 18 10011 23 13 13 19 10100 24 14 14 20

 

7. How to use   f-string print object

 

You can print custom objects with f-string. The default setting is that if you pass an object to an f-string expression, it will display the object  __ str__   Method. However, you can also print the value of _repr with the explicit conversion operation flag.

 

  • ! r - use   repr() converts the value to text

  • ! s - use   str()   Convert values to text

>>> class Color:    def __init__(self, r: float = 255, g: float = 255, b: float = 255):        self.r = r        self.g = g        self.b = b
def __str__(self) -> str: return "A RGB color"
def __repr__(self) -> str: return f"Color(r={self.r}, g={self.g}, b={self.b})"
>>> c = Color(r=123, g=32, b=255)
# If you don't add any operators, Can print __str__ Value of>>> f"{c}"'A RGB color'
# use`obj!r` It will be printed if necessary __repr__ Value of>>> f"{c!r}"'Color(r=123, g=32, b=255)'
#  Use! S as default > > >   f"{c!s}"'A RGB color'

Python also allows you to use the _format method to control formatting results by defining different types. The following example shows all possible cases.

>>> class Color:    def __init__(self, r: float = 255, g: float = 255, b: float = 255):        self.r = r        self.g = g        self.b = b
def __str__(self) -> str: return "A RGB color"
def __repr__(self) -> str: return f"Color(r={self.r}, g={self.g}, b={self.b})"
>>> c = Color(r=123, g=32, b=255)
# When no option is passed, the __str__ result is printed>>> f"{c}"'A RGB color'
# When `obj!r` is used, the __repr__ output is printed>>> f"{c!r}"'Color(r=123, g=32, b=255)'
# Same as the default>>> f"{c!s}"'A RGB color'Python also allows us to control the formatting on a per-type basis through the __format__ method. The following example shows how you can do all of that.
>>> class Color: def __init__(self, r: float = 255, g: float = 255, b: float = 255): self.r = r self.g = g self.b = b
def __str__(self) -> str: return "A RGB color"
def __repr__(self) -> str: return f"Color(r={self.r}, g={self.g}, b={self.b})"
def __format__(self, format_spec: str) -> str: if not format_spec or format_spec == "s": return str(self)
if format_spec == "r": return repr(self)
if format_spec == "v": return f"Color(r={self.r}, g={self.g}, b={self.b}) - A nice RGB thing."
if format_spec == "vv": return ( f"Color(r={self.r}, g={self.g}, b={self.b}) " f"- A more verbose nice RGB thing." )
if format_spec == "vvv": return ( f"Color(r={self.r}, g={self.g}, b={self.b}) " f"- A SUPER verbose nice RGB thing." )
raise ValueError( f"Unknown format code '{format_spec}' " "for object of type 'Color'" )
>>> c = Color(r=123, g=32, b=255)
>>> f'{c:v}''Color(r=123, g=32, b=255) - A nice RGB thing.'
>>> f'{c:vv}''Color(r=123, g=32, b=255) - A more verbose nice RGB thing.'
>>> f'{c:vvv}''Color(r=123, g=32, b=255) - A SUPER verbose nice RGB thing.'
>>> f'{c}''A RGB color'
>>> f'{c:s}''A RGB color'
>>> f'{c:r}''Color(r=123, g=32, b=255)'
>>> f'{c:j}'---------------------------------------------------------------------------ValueError Traceback (most recent call last)<ipython-input-201c0ee8dd74be> in <module>----> 1 f'{c:j}'
<ipython-input-15985c4992e957> in __format__(self, format_spec) 29 f"- A SUPER verbose nice RGB thing." 30 )---> 31 raise ValueError( 32 f"Unknown format code '{format_spec}' " "for object of type 'Color'" 33 )
ValueError: Unknown format code 'j' for object of type 'Color'

Finally, there is an a operator to escape ASCII characters. For more information, refer to:

docs.python.org/3/library/functions.html#as..

 

>>> utf_str = "Áeiöu"
>>> f"{utf_str!a}""'\\xc1ei\\xf6u'"

 

8. How to set floating point precision with f-string

F-string can format floating-point numbers like str.format. To do this, you need to add one  : (colon) add another one  . (English period) followed by the number of decimal places, and finally ended with f.

 

For example, you can print an approximation of a floating-point number to the nearest percentile by the following code.

>>> num =4.123956>>> f"num rounded to 2 decimalpalces = {num:.2f}"'num rounded to 2 decimal palces = 4.12'

Without any options, the exact value of the floating point number itself is printed.

>>> print(f'{num}')4.123956

 

9. How to format a number as a percentage

 

Python f-string method has a very convenient operation method to format percentage. The method is similar to floating-point number format, but use% instead of the ending F. it will multiply the original value by 100 and display it in a fixed format with percentage symbol. The accuracy can also be set.

>>> total = 87
>>> true_pos = 34
>>> perc = true_pos / total
>>> perc0.39080459770114945
>>> f"Percentage of true positive: {perc:%}"'Percentage of true positive: 39.080460%'
>>> f"Percentage of true positive: {perc:.2%}"'Percentage of true positive: 39.08%'

 

10. How to adjust or increase   f-string   Filling of

 

You can pass easily  < Or use the > symbol to adjust the string fill.

 

 

>>> greetings = "hello"
>>> f"She says {greetings:>10}"'She says hello'
# Pad 10 char to the right>>> f"{greetings:>10}"' hello'
>>> f"{greetings:<10}"'hello '
# You can omit the < for left padding>>> f"{greetings:10}"'hello '

 

>>> a = "1"
>>> b = "21"
>>> c = "321"
>>> d = "4321"
>>> print("\n".join((f"{a:>10}", f"{b:>10}", f"{c:>10}", f"{d:>10}"))) 1 21 321 4321

 

11. How to escape symbols

 

If you want to print the variable name enclosed in braces instead of the value of the variable, you need double braces   {{}}.

>>> hello = "world"
>>>f"{{hello}} = {hello}"'{hello} = world'

 

If you want to escape double quotation marks, you need to use a backslash before the quotation marks  \  Mark.

>>>f"{hello} = \"hello\""'world = "hello"'

 

12. How to center a string

 

To achieve string centering, you can use var:^N. Where var is the variable you want to print, and N is the string length. If n is less than the length of var, all strings are printed.

>>> hello = "world">>>f"{hello:^11}"
' world '>>>f"{hello:*^11}"'***world***'
# Extra padding is added to the right>>>f"{hello:*^10}"'**world***'
# N shorter than len(hello)>>>f"{hello:^2}"'world'

 

13. How to format thousands

 

F-string also allows us to customize the format of digital display. A very common requirement is to separate numbers with an underscore every three digits.

>>> big_num = 1234567890
>>> f"{big_num:_}"'1_234_567_890'

 

thirteen point one   How to use commas and thousands separator numbers

 

In fact, you can use any symbol as a thousandth separator. So there's no problem with commas as as separators.

>>> big_num = 1234567890
>>> f"{big_num:,}"'1,234,567,890'

 

You can even handle floating-point numbers with both thousandth separator and precision setting at the same time.

>>> num =2343552.6516251625>>> f"{num:,.3f}"'2,343,552.652'

 

thirteen point two   How to use spaces as thousands separator

Can I use a space?

Well, it's a tough problem, but it can be achieved. You can use commas as as separators and then replace commas with spaces.

>>> big_num = 1234567890
>>> f"{big_num:,}".replace(',',' ')'1 234 567 890'

Another way is to set your local language environment and replace it with an environment with spaces as thousand separator, such as pl_PL (Polish environment). For more information, please refer to this Stack Overflow link:

https://stackoverflow.com/a/17484665

 

14. How to display a number by scientific counting (exponential counting)

 

It can be formatted with E or e characters.

 

>>> num =2343552.6516251625>>>f"{num:e}"
'2.343553e+06'>>> f"{num:E}"
'2.343553E+06'>>> f"{num:.2e}"
'2.34e+06'>>> f"{num:.4E}"'2.3436E+06'

 

15. Use in f-string   if-else

 

F-string can also calculate slightly more complex expressions, such as if/else

 

>>> a = "this is a">>> b = "this is b"
>>> f"{a if 10 > 5 else b}"'this is a'
>>> f"{a if 10 < 5 else b}"'this is b'

 

16. How in   Use dictionary in f-string

 

You can use dictionaries in f-string s. The only requirement is that the quotation marks that cause the entire string should be different from the internal quotation marks.

>>>color = {"R": 123, "G": 145, "B": 255}>>> f"{color['R']}"'123'>>> f'{color["R"]}'
''123'There's a mistake here. It should be'123'bar>>> f"RGB = ({color['R']},{color['G']}, {color['B']})"
'RGB = (123, 145, 255)'

 

17. How to use   f-string splicing string

 

Merging f-string s is the same as ordinary string splicing. You can implicitly splice them directly, or explicitly use the plus sign +, or use the str.join method.

# Implicit string splicing>>> f"{123}" " = "f"{100}" " + " f"{20}" " + "f"{3}"'123 = 100 + 20 + 3'
# Use plus sign + Explicit string splicing>>> f"{12}" + " != "+ f"{13}"'12 != 13'
# use str.join String splicing>>> "".join((f"{13}", f"{45}"))'13 45'
>>>"#".join((f"{13}", f"{45}"))'13#45'

 

18. How to format datetime   object

 

F-string also supports the formatting of datetime objects. The process is very similar to the method of str.format formatting dates. Please refer to the tables in the official documentation for more information on the supported formats.

>>> import datetime>>> now = datetime.datetime.now()>>> ten_days_ago = now -datetime.timedelta(days=10)>>> f'{ten_days_ago:%Y-%m-%d %H:%M:%S}'
'2020-10-13 20:24:17'>>> f'{now:%Y-%m-%d %H:%M:%S}''2020-10-23 20:24:17'

19. How to fix the illegal format error of f-string

 

If it is not used correctly, f-string will report format error. The most common mistake is to put double quotation marks inside double quotation marks. Single quotation marks cause the same error.

>>>color = {"R": 123, "G": 145, "B": 255}
>>> f"{color["R"]}" File"", line 1   f"{color["R"]}"   ^SyntaxError: f-string: unmatched '['
>>> f'{color['R']}'  File"", line 1   f'{color['R']}'   ^SyntaxError: f-string: unmatched '['

 

  Another common mistake is to use f-string in older versions of python. Only python 3.6 introduced f-string. If you use this method in previous versions, the interpreter will report format errors   SyntaxError: invalid syntax.

>>> f"this is an old version" File"", line 1   f"this is an old version"
SyntaxError: invalid syntax

If you see this error, first determine the current python version. The method I checked was to get the version number by calling sys.version under python 2.7.

>>> import sys;print(sys.version)2.7.18 (default, Apr 202020, 19:27:10)[GCC 8.3.0]

 

20. How to fill zero before string

 

You can use {expr:0len}   This method is used for string zeroing. Len is the length of the final returned string. You can also add a sign mark. In this case, use + to display the corresponding sign regardless of whether the value is positive or negative. Use - to display a negative sign only when the value is negative, as is the default setting. Refer to this link for more information

https://docs.python.org/3/library/string.html#format-specification-mini-language

>>> num = 42
>>> f"{num:05}"'00042'
>>> f'{num:+010}''+000000042'
>>> f'{num:-010}''0000000042'
>>> f"{num:010}"'0000000042'
>>> num = -42
>>> f'{num:+010}''-000000042'
>>> f'{num:010}''-000000042'
>>> f'{num:-010}''-000000042'

 

21. How to handle multiline f-string (processing of newline character)

 

You can use the newline character \ nto print multiple lines of text.

>>> multi_line = (f'R: {color["R"]}\nG: {color["G"]}\nB: {color["B"    ...: ]}\n')
>>> multi_line'R: 123\nG: 145\nB: 255\n'
>>> print(multi_line)R: 123G: 145B: 255

You can also implement multiline strings with three quotation marks. This can not only add line breaks, but also have tabs.

>>> other = f"""R:{color["R"]}    ...: G:{color["G"]}    ...: B:{color["B"]}    ...:""">>> print(other)
R: 123G: 145B: 255

use   Code example for Tab

>>> other = f'''    ...:this is an example    ...:    ...:^Iof color {color["R"]}   ...:        ...: '''
>>> other
'\nthis is an example\n\n\tof color 123\n \n'
>>> print(other)this is an example    of color123
>>>

 

22. Conclusion

 

That's all for this article! I hope you have learned some novel and practical knowledge. Knowing how to make full use of f-string can definitely make life better.

Posted by LuiePL on Sat, 27 Nov 2021 23:50:33 -0800