Fundamentals 10 min read

Master Python f-strings: Syntax, Tricks, and Real-World Examples

This tutorial explains Python 3.6's f‑string formatting, covering basic usage, expression evaluation, lambda functions, quoting rules, brace escaping, padding, numeric specifiers, width/precision control, date formatting, and a complete multiplication‑table case with code samples.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python f-strings: Syntax, Tricks, and Real-World Examples

1. f‑string Introduction

Python 3.6 introduced a new string‑formatting method called f‑string . Compared with %s and str.format(), f‑strings are more intuitive, faster, and simpler to use.

f‑strings build on the concepts of format(), so learning %s and format() first is helpful.

2. Common f‑string Usage

2.1 Basic Usage

Expressions are placed inside curly braces {} and are evaluated at runtime.

name = "Huang Wei"
f"Hello, my name is {name}"  # 'Hello, my name is Huang Wei'
num = 2
f"I have {num} apples"          # 'I have 2 apples'
price = 95.5
f"He has {price}$"               # 'He has 95.5$'

2.2 Expression Evaluation & Function Calls

f"They have {2+5*2} apples"          # 'They have 12 apples'
name = "Huang Wei"
f"my name is {name.lower()}"      # 'my name is huang wei'
import math
f"Π的值为{math.pi}"                # 'Π的值为3.141592653589793'

2.3 Using Lambda in f‑strings

aa = 123.456
f"{(lambda x: x*5-2)(aa):.2f}"   # '615.28'
bb = 8
cc = 2
f"{(lambda x,y: x+y)(bb,cc)}"    # '10'

Note: the first parentheses enclose the lambda expression, the second passes arguments.

2.4 Quote Handling

Quotes inside the braces must not conflict with the outer string delimiters. Use different combinations of single, double, triple quotes as needed.

f'I am {"Huang Wei"}'   # 'I am Huang Wei'
f'''I am {'Huang Wei'}'''   # 'I am Huang Wei'
f"I am {'Huang Wei'}"   # 'I am Huang Wei'

Backslashes cannot appear inside the expression part.

2.5 Escaping Braces

To display a literal brace, double it: {{ or }}.

f"5{{apples}}"   # '5{apples}'
f"{{5}}{apples}" # '{5}apples'

2.6 Padding

Use >, <, or ^ for left, right, or center padding. A fill character can be specified before the alignment symbol.

name = "Huang Wei"
f"{name:>20}"   # '           Huang Wei'
f"{name:<20}"   # 'Huang Wei           '
f"{name:^20}"   # '   Huang Wei   '
f"{name:_>20}"  # '___________Huang Wei'

2.7 Numeric Sign Specifiers

a = 12
b = -25
f"{a:+}"   # '+12'
f"{b:+}"   # '-25'
f"{a:-}"   # '12'
f"{b:-}"   # '-25'
f"{a: }"   # ' 12'
f"{b: }"   # '-25'

2.8 Width & Precision

a = 123.456
f"{a:10}"      # '   123.456'
f"{a:010}"     # '000123.456'
f"{a:8.1f}"    # '   123.5'
f"{a:8.2f}"    # '  123.46'
f"{a:.2f}"     # '123.46'
f"{a:2f}"      # '123.456000'

2.9 Truncation & Padding Combination

a = "Hello"
f"{a:10.3}"    # 'Hel       '
f"{a:_>10.3}"   # '_______Hel'
f"{a:_<10.3}"   # 'Hel_______'

2.10 Date/Time Formatting

from datetime import *
a = date.today()
f"{a:%Y-%m-%d}"   # '2020-02-01'

3. Comprehensive Example: Multiplication Table

Printing the 9×9 multiplication table using three formatting methods.

3.1 Using % Operator

for i in range(1,10):
    for j in range(1,i+1):
        print("%s*%s=%s" % (j,i,j*i), end=" ")
    print("
")

3.2 Using format()

for i in range(1,10):
    for j in range(1,i+1):
        print("{0}*{1}={2}".format(j,i,j*i), end=" ")
    print("
")

3.3 Using f‑strings

for i in range(1,10):
    for j in range(1,i+1):
        print(f"{j}*{i}={j*i}", end=" ")
    print("
")

All three approaches produce the same formatted multiplication table.

f‑string diagram
f‑string diagram
width and precision diagram
width and precision diagram
multiplication table using %
multiplication table using %
multiplication table using format
multiplication table using format
multiplication table using f‑string
multiplication table using f‑string
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonCode ExamplesTutorialstring formattingf-string
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.