String formatting inserts variables and expressions into strings in a structured, readable way. It produces dynamic output and makes text in programs clearer.
Five Ways to Format Strings
- The
%operator - The
format()method - f-strings (formatted string literals)
- The
Templateclass - The
center()method
1. The % Operator
This is the oldest formatting method. The % operator is also called the "string-formatting operator."
In "The mangy, scrawny stray dog %s gobbled down" % 'hurriedly', the %s placeholder is replaced by 'hurriedly'.
print("The mangy, scrawny stray dog %s gobbled down" %'hurriedly' +
"the grain-free, organic dog food.")Output:
The mangy, scrawny stray dog hurriedly gobbled downthe grain-free, organic dog food.Multiple Strings
Pass a tuple to insert several values.
x = 'looked'
print("Misha %s and %s around"%('walked',x))Output:
Misha walked and looked aroundPrecision for Floats
Floats use the format %a.bf. Here a is the minimum total width, padded with spaces if the number is shorter, and b is the number of digits after the decimal point.
The specifier %5.4f below sets a minimum width of 5 and 4 decimal places.
print('The value of pi is: %5.4f' %(3.141592))Output:
The value of pi is: 3.1416Multiple Conversion Types
%d converts to an integer and %f to a float.
variable = 12
string = "Variable as integer = %d \n\
Variable as float = %f" %(variable, variable)
print (string)Output:
Variable as integer = 12
Variable as float = 12.0000002. The format() Method
format() was introduced to handle complex formatting more efficiently. Replacement fields, marked by curly braces {}, are placed in the string, and the values to insert are passed as arguments to str.format().
Syntax:
'String here {} then also {}'.format('something1','something2')Basic usage:
print('We all are {}.'.format('equal'))Output:
We all are equal.Index-Based Insertion
Numbers inside the braces select which argument goes where.
print('{2} {1} {0}'.format('directions','the', 'Read'))Output:
Read the directionsKeyword Arguments
Named placeholders are filled by matching keyword arguments.
print('a: {a}, b: {b}, c: {c}'.format(a = 1,b = 'Two',c = 12.3))Output:
a: 1, b: Two, c: 12.3Reusing a Value
One named argument can fill several placeholders.
print(
'The first {p} was alright, but the {p} {p} was tough.'.format(p='second'))Output:
The first second was alright, but the second second was tough.Float Precision
Syntax:
{[index]:[width][.precision][type]}Available type codes:
d: integersf: floating-point numbersb: binary numberso: octal numbersx: hexadecimal numberss: stringse: floating-point numbers in exponent notation
Below, the same value is formatted with % and then with .format():
print('The valueof pi is: %1.5f' %3.141592)
print('The valueof pi is: {0:1.5f}'.format(3.141592))Output:
The valueof pi is: 3.14159
The valueof pi is: 3.141593. f-Strings
PEP 498 introduced Literal String Interpolation, better known as f-strings because of the f prefix on the string. Its goal is to make interpolation simpler.
To create one, put f before the opening quote. Formatting works much like str.format(), and Python expressions can be embedded directly in the string.
name = 'John'
print(f"My name is {name}.")Output:
My name is John.Any Python expression can go inside the braces, including arithmetic.
Arithmetic
a = 5
b = 10
print(f"He said his age is {2 * (a + b)}.")Output:
He said his age is 30.Lambda Expressions
Lambdas also work. Here lambda x: x*2 doubles its argument.
print(f"He said his age is {(lambda x: x*2)(3)}")Output:
He said his age is 6Float Precision
Syntax:
{value:{width}.{precision}}num = 3.14159
print(f"The valueof pi is: {num:{1}.{5}}")Output:
The valueof pi is: 3.14164. The Template Class
The Template class in the string module offers simplified syntax for specifying output. Placeholders start with $ followed by a valid Python identifier (letters, digits, underscores). Wrapping a placeholder in braces lets letters follow it without a space. Writing $$ produces a literal $.
The code below imports Template, builds a template with placeholders $n3 and $n4, and fills them with the values of n1 and n2.
from string import Template
n1 = 'Hello'
n2 = 'New World'
n = Template('$n3 ! This is $n4.')
print(n.substitute(n3=n1, n4=n2))Output:
Hello ! This is New World.5. The center() Method
str.center() returns a new string centered within a given width, padded with spaces on both sides.
string = "Hello World!"
width = 30
centered_string = string.center(width)
print(centered_string)Output:
Hello World!Comparison: % vs .format() vs f-strings
f-strings are faster and generally better than both % formatting and str.format(). Their expressions are evaluated at runtime and merged with the literal part of the string to produce the final result, using simple syntax.