dev.rean.me
python

07 How to Use String Format in Python + Tips (Video in Khmer)

Learn Python string format with f-string, format() and % with simple example and tips. Short and clear. Good for beginner!

2026-10-20 ยท 4 min read

Share:

Hello friend! ๐Ÿ‘‹ You want put variable inside text? Use string format!

In this post, I show you string format in Python. Easy and short. ๐Ÿ


๐Ÿค” Why String Format?

Join text with + is hard to read:

name = "Dara"
age = 20

print("My name is " + name + " and I am " + str(age) + " years old.")

String format is cleaner. No need str().

print(f"My name is {name} and I am {age} years old.")

Python have 3 way to format string:

WayExample
f-stringf"Hi {name}"
format()"Hi {}".format(name)
%"Hi %s" % name

Use f-string. It is newest and best.


โœจ Way 1: f-string

Put f before the quote. Put variable inside { }.

name = "Dara"
price = 2.5
qty = 3

print(f"Hello {name}")                 # Hello Dara
print(f"Total: {price * qty}")          # Total: 7.5
print(f"Upper: {name.upper()}")         # Upper: DARA

You can run code inside { }.

๐ŸŽฅ Video: String Formatting in Python Part 1 (Khmer)


๐Ÿงฉ Way 2: format()

Use {} as empty place. Then put value in format().

print("Hello {}".format("Dara"))                  # Hello Dara
print("{} is {} years old".format("Dara", 20))    # Dara is 20 years old
print("{1} {0}".format("World", "Hello"))         # Hello World  (by position)
print("{name} is {age}".format(name="Sok", age=25))  # Sok is 25

๐Ÿ”ฃ Way 3: % Operator (Old Style)

You may see this in old code.

name = "Dara"
age = 20

print("Hello %s" % name)                    # %s = string
print("I am %d years old" % age)            # %d = integer
print("Price: %.2f" % 3.14159)              # %f = float -> 3.14
print("%s is %d years old" % (name, age))   # many value use ( )

๐ŸŽจ Format Number

This is part 2. Control how number look.

pi = 3.14159265
big = 1234567
rate = 0.256

print(f"{pi:.2f}")       # 3.14       2 digit after dot
print(f"{big:,}")        # 1,234,567  add comma
print(f"{rate:.1%}")     # 25.6%      percent
print(f"{5:03}")         # 005        fill 0, total 3 digit
print(f"{255:b}")        # 11111111   binary

๐Ÿ“ Align Text

print(f"|{'left':<10}|")      # |left      |
print(f"|{'right':>10}|")     # |     right|
print(f"|{'center':^10}|")    # |  center  |
print(f"|{'hi':*^10}|")       # |****hi****|  fill with *
  • < left
  • > right
  • ^ center

๐Ÿ“Š Example: Simple Table

items = [("Apple", 1.5), ("Banana", 0.75), ("Orange", 2)]

for name, price in items:
    print(f"{name:<10} ${price:>6.2f}")

Output:

Apple      $  1.50
Banana     $  0.75
Orange     $  2.00

๐ŸŽฅ Video: String Formatting in Python Part 2 (Khmer)


โŒ Common Error

Forget the f:

name = "Dara"
print("Hello {name}")

Output: Hello {name}. Python print it as normal text. Fix: add f.

print(f"Hello {name}")

Same quote inside f-string (older Python):

print(f"Name: {user["name"]}")    # error in Python before 3.12
print(f"Name: {user['name']}")    # good

Need show { } as text? Use double:

print(f"Use {{name}} like this")   # Use {name} like this

๐Ÿ’ก Tips

  • Use f-string first. Short, fast and easy to read.
  • Use :.2f for money or price. Always 2 digit after dot.
  • Use :, for big number. Easy to read: 1,000,000.
  • Use <, >, ^ to make nice table in terminal.
  • Use {value = } for quick debug: f"{age = }" โ†’ age = 20
  • Don't forget the f before quote!
  • Use format() when text come from variable or file (template).
  • Use % only when you read old code.

โ“ Any Question?

Tell us in comment below! ๐Ÿ‘‡

#Python #StringFormat #fstring #LearnPython #Beginner


๐Ÿ“š Related Post

โ† Back to python
Share: