What You’ll Learn

Four ways to handle string creation in Python:

What You’ll Need

The Python interpreter offers a convenient interactive command line for interacting and testing Python code in real time. This not a debugger per se—that is a different subject matter all on its own—but it does offer the ability to work with variables and methods interactively. This can be very helpful in testing or learning Python concepts.

Installation

For your given operating system, there may be more than a few ways to install and use Python. On most Linux distros, Python is installed on the system and is available for use pretty much out of the box. MacOS has Python—typically an older version—on the system, but it is not advised to use that version. There are multiple ways to have Python on modern versions of Windows, including the Linux subsystem for Windows.

For the purpose of these exercises, the demonstrations will be utilizing Python 3.6+ installed via a popular open-source software installation system known as Homebrew on macOS.

Download Python

Opening the Python Interactive Interpreter

On macOS (if installed correctly with Homebrew) and on Linux, you should simply be able to type python3 to start a version 3 Python interpreter.

Starting the Python Interpreter

When the Python interpreter starts, it outputs the version and how it was compiled.

Note: Exiting can be tricky. There are three ways: CTRL-D control sequence for terminating standard input, exit(), or quit(), which the last two are technically function calls.

Concatenation is taking multiple string variables and combining them into one bigger string, oftentimes used to combine variables with predefined string values resulting in a combined string output. While it is the simplest way to manipulate strings, but it doesn’t offer any sort of formatting without adding your own code to do so.

Let’s define a string and a numeric variable to use in our concatenation exercise.

Concat String Variables

Now that we have device_name and reboot_count variables, let’s concatenate them to print user-friendly output.

Concat String Print

As you can see, we took the two variables and created the string we wanted using concatenation. It’s really that simple, but not the simplest solution; you will see that later.

Note: Numeric values need to be type-cast to a string to be used in concatenation. This is done by using the str() function with the associate variable, for example str(reboot_count) turns the integer 3 into a string representation of 3.

Template strings provide a simpler substitution syntax that aligns well with internationalization (i18n) efforts.

Think of it this way: Template strings allow for a template to be defined and then later substitute the appropriate values to render the intended string.

Let’s try the following example. First, we need to import the Template method from the string class.

Template Import

We are using the from string import Template to bring the Template method into the main namespace.

Next, we define the string template. We are going to use the same example we used in the concatenation exercise.

Template String Template

With template strings, you’ll notice how we used $device and $count as the template variables. These do not have to be the same as the defined variables we will be using outside the template.

Now we need to apply the program variables to the template string using the substitute method for the template string.

Template String Substitute

As you can see, the resulting string used the template and passed variable substitutions to render the intended string.

Reference: Python 3 Documentation—Template strings

You may look at string formatting and think it is the same as template strings. Template strings are a less flexible way of creating strings with variables. String formatting gives you a lot of control in how the value of the variable is rendered. A great example is with numbers. With string formatting, you can define that when rendered a number, it needs to be four characters in length and “fill” the rest with spaces or preceding zeros. This gives you a lot of control over how the strings are rendered, making it possible to do fixed-width column output as an example.

Let’s do a simple string formatting exercise. We will be using our previous defined variables.

Format Render Positional

First, we have done the simplest form of string formatting, the use of undefined positional arguments. The first occurrence of {} in the string is the first argument of the .format() method. The second occurrence of {} is the second argument, and so forth.

Now let’s set the position of the arguments.

Format Render Positional Named

As you can see, it is similar to the previous usage of the .format() method, but now we have switched the arguments by setting the position in the string by using {1} and {0}.

Here is where things get more interesting! You can use named arguments with the .format() method.

Format Render Named

Within the {}, we can set a name, which then requires a named argument with the .format() method.

This is a pretty powerful and flexible way to format strings, but there is even more! There is a whole “mini-language” to specify how the values will be rendered.

Now let’s add str() typing to the {count} named argument by adding !s to the named argument so that we get {count!s}.

Format Render Named Mini

The result of adding to this formatting named argument is the variable is passed to str(), doing what we did in the concatenation example, changing the type from an integer to a string.

There are a set of standard format specifiers that can be used.

For more information on these specifiers and how to use them, check out the Python documentation at Format Specification Mini-Language.

Reference: Python 3 Documentation—Format String Syntax

Introduced in Python 3.6 was a new way of doing formatted strings called “formatted string literals” or, because of the way they are written in code, “f-strings.”

Let’s print an f-string formatted string!

f-string

The same Format Specification Mini-Language is used in f-strings as well, and for the reboot_count, you can see the usage of !s. For more information, check out the Python documentation on Formatted String Literals.

Personally, out of all the solutions, I find f-strings to be the most efficient from a standpoint of the act of coding and that they are pretty easy to understand when they are encountered in code.

While this is not meant to be an in-depth exploration of string formatting in the Python language, it should give you a basic understanding of its capabilities. When the need arises, now you have potential solutions when it comes to string formatting in Python.

Happy coding!

Training Resources

Learn More