Python String Formatting
String formatting in Python allows you to create dynamic strings by inserting variables into placeholders. There are different ways to format strings in Python, such as using format()
, f-strings (since Python 3.6), and the %
operator.
Example 1: Basic String Formatting using format()
The format()
method allows you to insert values into placeholders using curly braces {}
. You can pass values directly into the method or by using positional and keyword arguments.
# Basic string formatting with format()
name = "Karthick AG"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
Output
My name is Karthick AG and I am 30 years old.
Example 2: String Formatting using F-strings
F-strings, available in Python 3.6 and later, provide a concise and readable way to format strings. You can embed expressions inside curly braces directly into the string, prefixed with f
.
# String formatting with f-strings
name = "Durai"
age = 25
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
Output
My name is Durai and I am 25 years old.
Example 3: String Formatting using the Percentage Operator
The %
operator can also be used for string formatting. You can use it to insert values into strings by specifying the type (e.g., %s
for strings, %d
for integers).
# String formatting with % operator
name = "Vijay"
age = 28
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
Output
My name is Vijay and I am 28 years old.
Example 4: Formatting Numbers
You can format numbers using string formatting. This includes formatting numbers with a certain number of decimal places, adding commas to large numbers, and more.
# Formatting numbers example
pi = 3.141592653589793
formatted_pi = "The value of pi to 2 decimal places is {:.2f}".format(pi)
large_number = 1000000
formatted_large_number = "The large number is {:,}".format(large_number)
print(formatted_pi)
print(formatted_large_number)
Output
The value of pi to 2 decimal places is 3.14
The large number is 1,000,000
Example 5: Aligning and Padding Strings
Using string formatting, you can align text (left, right, center) and pad it with extra spaces or characters. This can be useful when displaying tables or aligning output.
# Aligning and padding example
name = "Rohini"
formatted_name = "|{:^10}|".format(name) # Center align within 10 characters
formatted_name_right = "|{:>10}|".format(name) # Right align
formatted_name_left = "|{:<10}|".format(name) # Left align
print(formatted_name)
print(formatted_name_right)
print(formatted_name_left)
Output
| Rohini |
| Rohini|
|Rohini |