String Formatting with Python's format() Method
The format() method formats a specified value and inserts it into placeholders within a string. Placeholders are denoted by curly braces {}. The method can accept one or more positional or named arguments which replace the braces.
Placeholder Replacement Methods
1. Positional Arguments
Arguments are passed in order to the format() method and fill the placeholders sequentially.
subject = 'Alex'
years = 25
print('{} is {} years old'.format(subject, years))
2. Indexed Arguments
Agruments can be referenced by their index within the format() call, starting from 0.
person_a = 'Emma'
person_b = 'David'
age_val = 40
print('{1} and {0} are both {2} years old'.format(person_a, person_b, age_val))
3. Named Arguments
Arguments can be assigned names within the format() call and referenced by those names in the placeholders.
print('{first} and {second} are both {age} years old'.format(first='Olivia', second='James', age=120))
4. Numeric Formatting For floating-point numbers, format specifiers can control precision and rounding.
value = 3.14159
print('Value rounded to two decimals: {:.2f}'.format(value))
Format Specifiers for Different Data Types
Integers Integer values can be formatted in different bases.
num = 42
# Binary
print('Binary: {:b}'.format(num))
# Decimal
print('Decimal: {:d}'.format(num))
# Octal
print('Octal: {:o}'.format(num))
# Hexadecimal (lowercase and uppercase)
print('Hex lowercase: {:x}, Hex uppercase: {:X}'.format(num, num))
# Unicode character
print('Unicode char: {:c}'.format(num))
Floating-Point Numbers Float formatitng includes scientific notation, fixed-point, and percentage representations.
float_num = 123.456789
# Scientific notation (lowercase 'e'), precision 2
print('Scientific (lowercase): {:.2e}'.format(float_num))
# Scientific notation (uppercase 'E'), precision 2
print('Scientific (uppercase): {:.2E}'.format(float_num))
# Fixed-point, precision 3
print('Fixed-point 3 decimals: {:.3f}'.format(float_num))
# Fixed-point (uppercase 'F'), handles inf/nan differently
print('Fixed-point uppercase: {:.2F}'.format(float_num))
# General format: switches between fixed and scientific based on exponent
print('General format (4 digits): {:.4g}'.format(float_num))
# Percentage, precision 1
print('Percentage: {:.1%}'.format(float_num))