As a Python programmer, it’s virtually guaranteed that you’ll need to master string concatenation and formatting.
Whether it’s preparing a message that will eventually be read by a user, or writing tools for internal use, knowing how to craft the perfect string is essential to the success of almost any program.
Communication is often the key to success. This is especially true in a world driven by data.
Fortunately, Python provides us with a wide set of tools that simplify the process of formatting strings. Mastering these tools will provide the skills needed to craft strings with precision.
Developing your Python skills will enable you to tackle a wide world of data, and all the exciting opportunities Python provides.
Concatenation
Joining two or more strings is a common task in any programming language. Doing so is referred to as concatenation. Python provides several tools for concatenating strings.
When we concatenate strings in Python, two or more strings are combined into a new string. It’s a bit like “adding” in mathematics, but instead of numbers, we’re adding strings.
The easiest way to concatenate strings in Python is to use the ‘+’ operator. In Python, the ‘+’ operator will join any two strings.
Here’s the syntax:
final_string = string_one + string_two
When we “add” strings in this way, we’re really concatenating them. As you can see, Python takes the concept of adding strings almost literally.
Let’s take a look at the ‘+’ operator at work with a code example.
Example 1: Concatenation in Python
# joining strings with the '+' operator
# first create two strings that we’ll combine
first_name = "Sherlock"
last_name = "Holmes"
# join the names, separated by a space character
full_name = first_name + " " + last_name
print("Hello, " + full_name + ".")
Output
Hello, Sherlock Holmes.
In this Python example, the ‘+’ operator is used to concatenate three strings and combine their values into a single, new string.
Using the ‘+’ operator is a straight-forward method for combining strings in Python.
After creating the variable full_name, our program uses the print() method to display the string in the command prompt. Using the ‘+’ operator, we format the string to include the proper punctuation, as well as add additional spacing.
Using the ‘+’ operator to concatenate strings is an excellent way to create more legible text. Creating human readable text is an important part of software design. Software is much easier to use when strings are properly formatted and the meaning is clear.
Multiple strings can be concatenated using longer Python statements.
Example 2: Combining multiple strings.
act1 = "This is the beginning"
act2 = "this is the middle"
act3 = "this is the end"
story = act1 + ", " + act2 + ", and " + act3 + "."
print(story)
Output
This is the beginning, this is the middle, and this is the end.
As you can see from the example above, there’s no limit on how many strings you can concatenate. By using the ‘+’ operator, it’s possible to concatenate many different strings.
It’s important to note that Python can’t concatenate objects of different types. For instance, it’s not possible to concatenate a string and a number. Doing so will cause Python to complain.
>>> str = "red"
>>> print(str + 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
Attempting to concatenate a string and an integer will cause an error. You can see from the Traceback message that Python can only concatenate a string with another string.
An easy solution to this problem is to use the str() method. Using this method will convert a number into a string.
>>> print("red" + " " + str(13))
red 13
The str() method simplifies the process of converting different types of data into string objects. This is a special Python method that works with many different types of objects. Use it to quickly convert numbers, decimals, and other objects into strings.
Example 3: Using the str() method to convert numbers to strings.
# use the str() method to convert numbers to strings
num = 221
letter = "B"
street = "Baker Street"
print(str(num) + letter + " " + street)
Output
221B Baker Street
String Formatting in Python
In order to precisely format text, it’s necessary to use more advanced techniques. Sometimes we would like to insert a variable into a string without using concatenation. This can be accomplished through a method known as interpolation.
With interpolation, Python dynamically interjects data into a string. Python provides multiple methods for interpolating data.
These methods are flexible and, depending on your needs, can be combined with other tools. Use them to precisely format strings and improve the readability of your Python programs.
String Formatting with the % Operator
One way to format strings in Python is with the ‘%’ operator. Use the ‘%’ operator to interject text into placeholders in a similar manner to how the format() method works.
When formatting strings with the ‘%’ operator, we must designate the type of data that will be substituted for the placeholder. This can be done with special characters.
For instance, the ‘s’ character is used to tell Python we want to substitute string data for the placeholder.
Suggested Reading: If you are into machine learning, you can read this article on regression in machine learning. You might also like this article on k-means clustering with numerical example.
Example 4: Using the % operator to interpolate data.
# %s for strings
# %d for numbers
print("%s never ends, %s." % ("Education","Watson"))
Output
Education never ends, Watson.
If we want to substitute other data types for the placeholder, we’ll need to use other special characters. For instance, you can pass an integer to the string buying using ‘%d’ as the placeholder in your string.
author = "Arthor Conan Doyle"
bday = 1859
print("%s was born on %d." % (author, bday))
String Formatting with the { } Operators
Formatting complex strings can be tedious. To ease the burden, Python provides a special method for interjecting data into a string.
With the format() method, placeholders are used to interject data into a string. The format() method will look for these placeholders in the string, and replace them with new values, provided as arguments to the method.
Placeholders are designated using the curly brackets.
Let’s take a look at the format() method at work.
Example 5: Using .format() to replace text in a string.
subject = "Dr. Watson"
clues = 3
message = "{}, I've found {} clues!".format(subject, clues)
print(message)
Output
Dr. Watson, I've found 3 clues!
Using the Join Method In Python
It’s also possible to identify placeholders using named indexes.
The join() method is used to concatenate a Python iterable. This method provides a quick way to convert a list or dictionary into string data.
This method is a powerful and versatile tool that can be useful to process lists or dictionaries of string data.
It’s a common task to print the contents of a Python list. With the join() method, a list of strings can be turned into a single string. The join() method requires a joiner, which is the character used to “glue” the list together.
For instance, if a comma is used as the joiner, the elements in the list will be separated by a comma in the final string. Any string can serve as the joiner, but it’s common to use something like a space to separate the strings.
Example 6: Joining strings with the join() method.
# create a list of string data
titles = ["A Study in Scarlet", "The Sign of Four", "A Scandal in Bohemia"]
# join the list using a comma and a space to separate the strings
print(', '.join(titles))
Output
A Study in Scarlet, The Sign of Four, A Scandal in Bohemia
The join() method can also be used to print the contents of a dictionary.
Example 7: Dictionaries and the join() method.
# use join() to print the characters in the dictionary
print(' '.join(characters))
# populate a list of occupations
occupations = []
for character in characters:
occupations.append(characters[character])
# use join to print the occupations
print(' '.join(occupations))
Output
Sherlock Watson Moriarty
In this example, we used the join() method to print both a dictionary and a list. As you can see, if join() is used to print a dictionary, only the dictionary’s keys are printed.
In order to see the values in the dictionary, it’s useful to create and populate a new list. This new list will hold the values assigned to the keys in the dictionary.
After creating and populating a new list, named “occupations”, we can use join() to print the list.
Detective Doctor Criminal Mastermind
Related Posts
Learning to properly format strings is an important skill that every Python programmer will need. Python provides several tools to accomplish this task. Mastering these tools will ensure that your programs are as legible and useful as they can be.
There are several ways to improve your skills in this area. The simplest would be to practice your new found Python skills and build some programs of your own. Building a text-based game, for example, would be an excellent way to practice concatenation and formatting strings.
Additional resources are available for students. If you’re interested in more information regarding Python programming, follow the links below.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.