{{announcement.body}}
{{announcement.title}}

Python String Format Examples: Substitution, Concatenation, and More

DZone 's Guide to

Python String Format Examples: Substitution, Concatenation, and More

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.

· Web Dev Zone ·
Free Resource

Basic String Concatenation

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

Python




xxxxxxxxxx
1


 
1
days = 28
2
month = 'February"
3
 
          
4
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):

Python




xxxxxxxxxx
1


 
1
month = 'February'
2
 
          
3
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).

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

By passing in an index, 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.

Python




xxxxxxxxxx
1


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

Python




xxxxxxxxxx
1


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

Python




xxxxxxxxxx
1


 
1
months = 12
2
days = 365
3
avg_days_per_month = days/months
4
 
          
5
# The ':g' specifier formats the value as a 'general' number.
6
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: 

Python




xxxxxxxxxx
1


 
1
month = 'February'
2
 
          
3
my_string = f'This month is {month}!'
4
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

Topics:
python ,string formatting ,tutorial ,strings ,python 3 ,examples ,code snippets

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}