The most basic way to construct a dynamic string in Python is with simple concatenation.

This approach is simple, but it is messy, ineffecient, 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):

While also valid, this approach is more or less obsolete (Python 3 introduced the format() method, which was back-ported to Python 2.7).

You may also like:
Six Python Tips for Beginners

Introduction to the format() Method

That brings us to Python’s 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

The index argument is positional and allows you to insert items from a list. In this example, 'world' is the first (index 0) item in our list, so it gets inserted.

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 substitution, where the keyword references the key in a key-value pair.

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. 

(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


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: 

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 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

Source link

Write A Comment