String Formatting in Python is the process of dynamically inserting values into a string. It allows you to create templates for text where specific parts can be replaced by variables, expressions, or function results.
In modern Python, there are three primary ways to format strings, each representing an evolution in the language's syntax.
Readability: It is much cleaner than using "string concatenation" (joining strings with +).
Precision: You can control how numbers are displayed (e.g., rounding decimals).
Data Injection: It allows you to build complex messages, like automated emails or UI labels, using dynamic data.
Old Style (% Operator): The original way, inherited from C-style programming.
New Style (.format() method): Introduced in Python 2.6 to provide more power and flexibility.
f-Strings (Literal String Interpolation): Introduced in Python 3.6. It is the fastest and most readable method available today.
f-strings are defined by prefixing a string with f or F. You place variables or expressions directly inside curly braces {}.
name = "Admin" score = 95.567 # Basic usage print(f"Hello, {name}!") # Expressions inside braces print(f"Next year, you will be {20 + 1} years old.") # Number formatting (Round to 2 decimal places) print(f"Your score is {score:.2f}")
This method uses placeholders {} within a string and passes arguments into the .format() function.
animal = "dog" action = "barks" # Positional formatting print("The {} {}.".format(animal, action)) # Index-based formatting print("The {1} {0}.".format(action, animal)) # Named placeholders print("User: {user}, Role: {role}".format(user="Arjun", role="Instructor"))
Though less common now, you will still see this in older codebases.
# %s for string, %d for integer, %f for float name = "EMBLAb" print("Welcome to %s" % name)
String formatting is particularly powerful when you need to align text in tables or format currency.
| Feature | Code Example | Output |
| Decimal places | f"{3.14159:.2f}" | 3.14 |
| Padding (Width) | f"{'Hi':>10}" | Hi (Right align) |
| Percentage | f"{0.25:.0%}" | 25% |
| Thousands Sep | f"{1000000:,}" | 1,000,000 |
Always use f-strings if you are using Python 3.6 or higher. They are more concise and execute faster than .format().
Use .format() only if you need to support very old versions of Python or if the formatting string is being passed as a variable from an external source.
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION