String Formatting
- String formatting in Python allows you to combine text with variables and values in a clean and readable way. Instead of joining strings manually, Python provides powerful formatting methods such as the format() method and f-strings. These methods make it easy to insert values into strings, control output structure, and improve code readability.
String Formatting in Python
String formatting allows dynamic insertion of variables into strings at runtime.
It helps create clear, readable, and professional messages.
Python supports multiple formatting sty les to suit different use cases.1. format() Method
The format() method replaces {} placeholders with values in the same order.
It is flexible, readable, and works in all modern Python versions.
Useful when formatting strings dynamically.
String Formatting Using format()
This code uses the format() method to insert variable values into a string and then prints the formatted message.
name = "Amit"
age = 22
msg = "My name is {} and I am {} years old".format(name, age)
print(msg)
2. f-Strings
f-strings allow variables and expressions to be placed directly inside strings.
They are faster, cleaner, and more readable than other methods.
Recommended approach in modern Python.
String Formatting Using f-Strings
This code uses an f-string to directly embed variable values inside a string and prints the result.
msg = f"My name is {name} and I am {age} years old"
print(msg)
3 Positional Formatting
Positional formatting assigns values to placeholders using index numbers.
It allows reordering of values inside the string.
Useful when the same value needs to appear multiple times.
Positional String Formatting
This code uses positional indexes with the format() method to insert values into a string in a specific order.
msg = "My name is {1} and I am {0} years old".format(age, name)
print(msg)
4. Named Formatting
Named formatting assigns values using named placeholders.
It improves readability and reduces confusion in large templates.
Best for complex or long strings.
Named Placeholders in String Formatting
This code uses named placeholders with the format() method to insert values into a string by specifying variable names.
msg = "My name is {n} and I am {a} years old".format(n=name, a=age)
print(msg)