3 ways to format strings in Python
In Python versions 3.6 and above, literal string interpolation receives the hype; however, did you know that there are several ways to format strings in Python?
String Formatting (printf-style)
String objects have a built-in operation: the % operator (modulo).
If the operator is used once in a string, then a single non-tuple object may be used:
1>>> "Ogres are like %s" % "onions"
2'Ogres are like onions'
In this example, the conversion type, %s
(string), will be replaced by “onions”.
Otherwise, the strings must be placed within a tuple of exact length or a dictionary.
Tuple:
1>>> "%s are like %s" % ("Ogres", "onions")
2'Ogres are like onions'
Dictionary:
1>>> "%(character)s are like %(vegetable)s" % {"character": "Ogres", "vegetable": "onions"}
2'Ogres are like onions'
Additionally, there are flag characters and other types. To represent an integer, the type %d
(for decimal) could be used. In the example below, %d
was used in combination with the 0
flag character to add trailing zeros.
1>>> "%03d - License to kill" % 7
2'007 - License to kill'
More information can be found here about the printf-style string formatting.
String Format Method
While the predecessor leveraged type conversions and flag characters, Python 3 introduced the str.format(*args, **kwargs)
string method.
Using positional arguments:
1>>> "{}, {}, {}".format("one", "two", "three")
2'one, two, three'
Using indices:
1>>> "{2}, {1}, {0}".format("apple", "orange", "cow")
2'cow, orange, apple'
Using repeated indices:
1>>> "{1}, it's {0}. Why {0}?".format(13, 'Naturally')
2"Naturally, it's 13. Why 13?"
Named arguments:
1>>> "{character} are like {food}".format(character="Ogres", food="onions")
2'Ogres are like onions'
Accessing arguments’ items:
1>>> coord = (1, 5)
2>>> "Plot the coordinate: ({0[0]}, {0[1]})".format(coord)
3'Plot the coordinate: (1, 5)'
Thousands separator:
1>>> "It's over {:,}!".format(9000)
2"It's over 9,000!"
… and more format string syntax tricks here.
Literal String Interpolation
Python 3.6 introduced literal string interpolation, also known as f-strings. F-strings allow you to embed expressions inside string constants.
1>>> pet_name = "Toto"
2>>> state = "Kansas"
3>>> f"{pet_name}, I've a feeling we're not in {state} anymore."
4"Toto, I've a feeling we're not in Kansas anymore"
F-strings are prefixed with the letter f
and allow you to complete operations inline within the string.
1>>> f"3 + 5 = {3+5}"
2'3 + 5 = 8'
The existing syntax from the str.format()
method can be used.
1>>> f"It's over {9000:,}!"
2"It's over 9,000!"