Index
What is String Formatting?
String formatting lets you insert variables inside a string.
Instead of writing:
name = "Alice"
print("Hello " + name)
You can do:
print(f"Hello {name}")
Common Ways to Format Strings:
- f-strings (Recommended)
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
2. format()
method
name = "Bob"
print("Hello, {}!".format(name))
3. %
formatting (Old style)
name = "Charlie"
print("Hello, %s!" % name)
Example:
price = 9.99
print(f"The price is ${price:.2f}") # Output: The price is $9.99