Python String Format Examples
In this brief introduction to string formatting in Python, we will explore live examples of string concatenation, string substitution, and additional formatting methods for common string operations.
Join the DZone community and get the full member experience.
Join For FreeAnytime you are programming something to be human-readable, you are bound to encounter lots of instances where you will need to format strings. Luckily Python offers a lot of different approaches for tackling strings. While I would not consider all of them best practices, it is always good to know what you can and cannot do. Below we will take a look at the many different options available for formatting strings in Python.
Basic String Concatenation
The most basic way to format a string in Python is with simple concatenation.
xxxxxxxxxx
days = 28
month = 'February"
my_string = month + ' is the shortest month of the year, with '+ str(days) + ' days.'
This approach is simple, but it is messy, inefficient, and prone to error (ever forget the spaces?), especially for complex, dynamic strings.
You may also be familiar with the %
operator (called a modulo), which allows you to perform string replacements like this (using a predefined variable "month" for substitution):
xxxxxxxxxx
month = 'February'
my_string = '%s is the shortest month of the year' % month
While also valid, this approach is more or less obsolete (Python 3 introduced the format()
method, which was back-ported to Python 2.7).
Introduction to the format() Method
That brings us to Python's native string format()
method. Introduced in Python 3, this method provides a simple way to construct and format strings with dynamic substitutions. Once you understand the basic syntax, this method offers a flexible way to construct strings that also happens to leave your code looking much cleaner (in my opinion).
With the format()
method, there are two primary substitution types, by index and by keyword.
Substitution by Index
By passing in an index (or positional argument), the format method will allow you to insert individual or multiple items from a list based on their index. In this example, 'world'
is the first (index 0) item in our list, so it gets inserted.
xxxxxxxxxx
my_string = 'Hello {0}!'.format('world','friend','there')
When we print our string to the console, we get: Hello world!
To see another example, try the interactive example below:
Example: Try changing the index values in the string!
Substitution by Keyword
The other approach is to use a keyword argument for substitution, where the keyword references the key in a key-value pair.
xxxxxxxxxx
my_string = "This month is {f}!".format(f='February')
If we print our string to the console, we get: This month is February!
Example: Using Variables
Number Formatting
The previous examples work for inserting strings into strings, but what if you want to insert a numeric value? For that, there are additional formatting specifiers that are appended to the value to specify the desired output format.
xxxxxxxxxx
months = 12
days = 365
avg_days_per_month = days/months
# The ':g' specifier formats the value as a 'general' number.
myString='On average, the months in a year have {0:g}.'.format(avg_days_per_month)
(If you don't include a format specifier for an integer, it will default to "general" format.)
Specifier | Formats Number As |
d | Decimal integer |
g | G | General number. Defaults to 6 levels of precision, or the min number of relevant levels. | "G" functions the same as "g" except that large numbers will be formatted with "E". |
f | Fixed point number. Defaults to 6 levels of precision. |
e | E | Scientific notation |
% | Converts value to a percentage |
n | Same as 'g' but uses the seperators of the current locale. |
Specifier | Converts Number To |
h | H | Hexidecimal (lower case | upper case) |
o | Octal |
b | Binary |
c | Unicode |
F-string (Literal String Interpolation, Oh My!)
With the release of Python 3.6, we were introduced to F-strings.
As their name suggests, F-strings begin with "f" followed by a string literal. We can insert values dynamically into our strings with an identifier wrapped in curly braces, just like we did in the format()
method. However, instead of an index that represents our value's position in a list or a key that maps to our value, we can use a variable name as our identifier.
Take the following example:
xxxxxxxxxx
month = 'February'
my_string = f'This month is {month}!'
print(my_string)
Here, our month
variable is placed directly into our string. {month}
is then replaced with month
's value, "February," when the F-string is evaluated. So, when my_string
prints to our terminal, we get This month is February!
. This removes some of the ambiguity that the previous methods added to string formatting. After all, why create a placeholder to represent a value that we reference later if we can use a single variable instead?
Another advantage of F-strings is that we don't have to account for variable types. Notice that num_normal_days
in the example above is an integer, 28. Previously, we would have had to use placeholders like %d
or :g
in order to add a numeric type to our string. With F-string, we don't have to tell our program that it's going to be looking at an integer inside of a string. Let's let Python do what it's good at — making our lives easier.
Note: When using properties of objects with F-strings, make sure to avoid dot notation and instead use braces. For example, if I had an object called month
and wanted to access its property, days
, I would use months['days']
as opposed to month.days
.
Additional Python String Methods
Python also offers a set of methods to help you programmatically transform your strings. Here is a list of a few methods worth making note of:
Method | Result |
capitalize() | Capitalizes the first letter of the string |
casefold() | Returns the string in all lowercase (useful for string matching according to the python documentation) |
count() | Counts all instances of a substring |
upper() | Returns the string in all uppercase letters |
split() | Splits string on designated seperator |
encode() | Returns an encoded string |
swapcase() | Swaps the case of each letter in the string |
More methods can be found in Python's String documentation.
Note: If you're interested in another formatting method in Python, check out their docs on String Templates.
Further Reading
Opinions expressed by DZone contributors are their own.
Comments