Programmers are destined to work with plenty of string data. This is partially because computer languages are tied to human language, we use one to create the other, and vice versa.
For this reason, it’s a good idea to master the ins and outs of working with strings early on. In Python, this includes learning how to join strings.
Manipulating strings may seem daunting, but the Python language includes tools that make this complex task easier. Before diving into Python’s toolset, let’s take a moment to examine the properties of strings in Python.
A Little String Theory
As you may recall, in Python, strings are an array of character data.
An important point about strings is that they are immutable in the Python language. This means that once a Python string is created, it cannot be changed. Changing the string would require creating an entirely new string, or overwriting the old one.
We can verify this feature of Python by creating a new string variable. If we try to change a character in the string, Python will give us a Traceback Error.
>>> my_string = "Python For Beginners"
>>> my_string[0]
'P'
>>> my_string[0] = 'p'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Its a good idea to keep the immutable quality of strings in mind when writing Python code.
While you can’t change strings in Python, you can join them, or append them. Python comes with many tools to make working with strings easier.
In this lesson, we’ll cover various methods for joining strings, including string concatenation. When it comes to joining strings, we can make use of Python operators as well as built-in methods.
As students progress, they’re likely to make use of each of these techniques in one way or another. Each has their own purpose.
Joining Strings with the ‘+’ Operator
Concatenation is the act of joining two or more strings to create a single, new string.
In Python, strings can be concatenated using the ‘+’ operator. Similar to a math equation, this way of joining strings is straight-forword, allowing many strings to be “added” together.
Let’s take a look at some examples:
# joining strings with the '+' operator
first_name = "Bilbo"
last_name = "Baggins"
# join the names, separated by a space
full_name = first_name + " " + last_name
print("Hello, " + full_name + ".")
In our first example, we created two strings, first_name and last_name, then joined them using the ‘+’ operator. For clarity, we added space between the names.
Running the file, we see the following text in the Command Prompt:
Hello, Bilbo Baggins.
The print statement at the end of the example shows how joining strings can generate text that is more legible. By adding punctuation through the power of concatenation, we can create Python programs that are easier to understand, easier to update, and more likely to be used by others.
Let’s look at another example. This time we’ll make use of a for loop to join our string data.
# some characters from Lord of the Rings
characters = ["Frodo", "Gandalf", "Sam", "Aragorn", "Eowyn"]
storyline = ""
# loop through each character and add them to the storyline
for i in range(len(characters)):
# include "and" before the last character in the list
if i == len(characters)-1:
storyline += "and " + characters[i]
else:
storyline += characters[i] + ", "
storyline += " are on their way to Mordor to destroy the ring."
print(storyline)
This more advanced example shows how concatenation can be used to generate human readable text from a Python list. Using a for loop, the list of characters (taken from the Lord of the Rings novels) is, one-by-one, joined to the storyline string.
A conditional statement was included inside this loop to check whether or not we’ve reached the last object in the list of characters. If we have, an additional “and” is included so that the final text is more legible. We’re also sure to include our oxford commas for additional legibility.
Here’s the final output:
Frodo, Gandalf, Sam, Aragorn, and Eowyn, are on their way to Mordor to destroy the ring.
This method will NOT work unless both objects are stings. For instance, trying to join a string with a number will produce an error.
>>> string = "one" + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
As you can see, Python will only let us concatenate a string to another string. It’s our jobs as programmers to understand the limitations of the languages we’re working with. In Python, we’ll need to make sure we’re concatenating the correct types of objects if we wish to avoid any errors.
Joining Lists with the ‘+’ Operator
The ‘+’ operator can also be used to join one or more lists of string data. For instance, if we had three lists, each with their own unique string, we could use the ‘+’ operator to create a new list combining elements from all three.
hobbits = ["Frodo", "Sam"]
elves = ["Legolas"]
humans = ["Aragorn"]
print(hobbits + elves + humans)
As you can see, the ‘+’ operator has many uses. With it, Python programmers can easily combine string data, and lists of strings.
Joining Strings with the .join() Method
If you’re dealing with an iterable object in Python, chances are you’ll want to use the .join() method. An iterable object, such as a string or a list, can be easily concatenated using the .join() method.
Any Python iterable, or sequence, can be joined using the .join() method. This includes, lists and dictionaries.
The .join() method is a string instance method. The syntax is as follows:
string_name.join(iterable)
Here’s an example of using the .join() method to concatenate a list of strings:
numbers = ["one", "two", "three", "four", "five"]
print(','.join(numbers))
Running the program in the command prompt, we’ll see the following output:
one,two,three,four,five
The .join() method will return a new string that includes all the elements in the iterable, joined by a separator. In the previous example, the separator was a comma, but any string can be used to join the data.
numbers = ["one", "two", "three", "four", "five"]
print(' and '.join(numbers))
We can also use this method to join a list of alphanumeric data, using an empty string as the separator.
title = ['L','o','r','d',' ','o','f',' ','t','h','e',' ','R','i','n','g','s']
print(“”.join(title))
The .join() method can also be used to get a string with the contents of a dictionary. When using .join() this way, the method will only return the keys in the dictionary, and not their values.
number_dictionary = {"one":1, "two":2, "three":3,"four":4,"five":5}
print(', '.join(number_dictionary))
When joining sequences with the .join() method, the result will be a string with elements from both sequences.
Copying Strings with ‘*’ Operator
If you need to join two or more identical strings, it’s possible to use the ‘*’ operator.
With the ‘*’ operator, you can repeat a string any number of times.
fruit = “apple”
print(fruit * 2)
The ‘*’ operator can be combined with the ‘+’ operator to concatenate strings. Combining these methods allows us to take advantage of Python’s many advanced features.
fruit1 = "apple"
fruit2 = "orange"
fruit1 += " "
fruit2 += " "
print(fruit1 * 2 + " " + fruit2 * 3)
Splitting and Rejoining Strings
Because strings in Python are immutable, it’s quite common to split and rejoin them.
The .split() method is another string instance method. That means we can call it off the end of any string object.
Like the .join() method, the .split() method uses a separator to parse the string data. By default, whitespace is used as the separator for this method.
Let’s take a look at the .split() method in action.
names = "Frodo Sam Gandalf Aragorn"
print(names.split())
This code outputs a list of strings.
['Frodo', 'Sam', 'Gandalf', 'Aragorn']
Using another example, we’ll see how to split a sentence into its individual parts.
story = "Frodo took the ring of power to the mountain of doom."
words = story.split()
print(words)
Using the .split() method returns a new iterable object. Because the object is iterable, we can use the .join() method we learned about earlier to “glue” the strings back together.
original = "Frodo took the ring of power to the mountain of doom."
words = original.split()
remake = ' '.join(words)
print(remake)
By using string methods in Python, we can easily split and join strings. These methods are crucial to working with strings and iterable objects.
Tying Up the Loose Ends
By now, you should have a deeper knowledge of strings and how to use them in Python 3. Working through the examples provided in this tutorial will be a great start on your journey to mastering Python.
No student, however, can succeed alone. That’s why we’ve compiled a list of additional resources provided by Python For Beginners to help you complete your training.
- Learn how to create a Python Dictionary.
- A beginner’s guide to Python List Comprehension.
With help, and patience, anyone can learn the basics of Python. If working to join strings in Python seems daunting, take some time to practice the examples above. By familiarizing yourself with string variables, and working with methods, you’ll quickly tap into the unlimited potential of the Python programming language.
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.