Python String Formatting Methods
1. Percent (%) Formatting (Old Style Formatting)
This is the oldest method of string formatting in Python. It uses % symbols similar to C language.
Common specifiers: %s for string, %d for integer, %f for float.
Example:
name = 'Preethi'
age = 20
print('My name is %s and I am %d years old.' % (name, age))
Float example:
price = 99.4567
print('Price = %.2f' % price)
(.2f means 2 decimal places)
2. .format() Method (Dot Format Method)
This method uses {} placeholders and is more flexible than % formatting.
Example:
name = 'Preethi'
age = 20
print('My name is {} and I am {} years old.'.format(name, age))
Float example:
num = 12.5678
print('Value = {:.2f}'.format(num))
3. Modulus (%) Operator in Strings
The modulus operator % is used to insert values into a string placeholder.
Example:
marks = 85
print('Your marks are %d' % marks)
Note: % is also used in math to find remainder, but in strings it formats values.
4. f-Strings (f' ') — Modern Method
This is the newest and easiest method (Python 3.6+). Variables are written directly inside {}.
Example:
name = 'Preethi'
age = 20
print(f'My name is {name} and I am {age} years old.')
Float example:
pi = 3.14159
print(f'Pi value = {pi:.2f}')
Summary:
Percent formatting - Old method
.format() - Flexible method
Modulus % - Same as percent formatting in strings
f-strings - Newest and easiest method