Dec. 09, 2012

String Concatenation and Formatting

One common task you’ll need to accomplish with any language involves merging or combining strings. This process is referred to as concatenation.

The best way to describe it is when you take two separate strings – stored by the interpreter – and merge them so that they become one.

For instance, one string would be “hello” and the other would be “world.” When you use concatenation to combine them it becomes one string, or “hello world”.

This post will describe how to concatenate strings in Python. There are different ways to do that, and we will discuss the most common methods. After, we will explore formatting, and how it works.

Concatenation

In Python, there are a few ways to concatenate – or combine - strings. The new string that is created is referred to as a string object. Obviously, this is because everything in Python is an object – which is why Python is an objected-oriented language.

In order to merge two strings into a single object, you may use the “+” operator. When writing code, that would look like this:

str1 = “Hello”
str2 = “World”
str1 + str2


The final line in this code is the concatenation, and when the interpreter executes it a new string will be created.

One thing to note is that Python cannot concatenate a string and integer. These are considered two separate types of objects. So, if you want to merge the two, you will need to convert the integer to a string.

The following example shows what happens when you try to merge a string and integer object. It was copied from David Bau’s personal website.

>>> print ‘red’ + ‘yellow’
Redyellow
>>> print ‘red’ * 3
Redredred
>>> print ‘red’ + 3
Traceback (most recent call last):
File “”, line 1, in
TypeError: cannot concatenate ‘str’ and ‘int’ objects
>>>


For reference, the “>>>” characters indicate where the interpreter is requesting a command.

Notice how multiplying the string “red” three times returns the value “redredred”. This is important, so be sure to record it to memory.

In addition, we can see when trying to combine ‘red’ and 3 the interpreter spits out an error. This is where we are trying to concatenate a string and integer object, and it failed.

In layman’s terms, a string can be any recorded characters but it’s most commonly used to store words and information. An integer on the other hand is a recorded number value that doesn’t have a decimal point. Python cannot add a word and number together. It makes sense why the error happens when you look at it this way.

To make this possible, we can convert the number into a string using the appropriate function. The code for that would look like this:

>>> print ‘red’ + str(3)
red3
>>>


The method we used to do this is the str() function. Notice how the interpreter simply combined the two objects and spit them out when it was asked to print the data?

String Formatting in Python

In Python, we can take advantage of two separate methods of string interpolation.

String interpolation is a term used to describe the process of evaluating a string value that is contained as one or more placeholders. To put it simply, it helps developers with string formatting and concatenation.

Hopefully, you are more familiar with the term yourself because it’s a crucial element of any programming language, especially Python.

String Formatting with the % Operator

Before we take a closer look, it’s important to understand that the % string operator will be deprecated – no longer used – in Python 3.1 and up. Eventually, it will be removed altogether from future versions of the language.

However, it’s still a good idea – and common practice – to become familiar with the method.

The best way to understand how to work with operators is to look at active code.

x = ‘apples
y = ‘lemons
z = “In the basket are %s and %s” % (x,y)


What this example code will do is replace the “%s” operator values with the corresponding string, in the order we have set. When you print the “z” string object - after executing the code above - it will return the following:

In the basket are apples and lemons

String Formatting with the { } Operators

When you use the curly braces or {} operators, they serve as place-holders for the variables you would like to store inside a string. In order to pass variables to a string you must call upon the format() method.

One benefit of using the format() method is that you do not have to convert integers into a string before concatenating the data. It will do that automatically for you. This is one reason why it is the preferred operator method.

Again, let’s take a look at some code showing this in action:

Fname = “John”
Lname = “Doe”
Age = “24”

print “{} {} is {} years old.“ format(fname, lname, age)


What this will do is take the appropriate values and store them as variables in the respective string.

Another useful feature of the format() method is that you don’t actually have to feed the inputs to the interpreter in the same order that you want the variables to be displayed, as long as you number the place-holders like so:

print “{0} {1} is {2} years old.” format(fname, lname, age)

 

Using the Join Method In Python

The join method in Python is used to concatenate a list of strings.

For example

>>>  .join([‘the’, ‘quick’, ‘brown’, ‘fox’, ‘jumps’, ‘over’, ‘the’, ‘lazy’, ‘dog’])
‘the quick brown fox jumps over the lazy dog’


Let’s create a new list that includes some great bands, but this time let’s do things differently.

>>> music = [“Metallica”, “Rolling Stones”, “ACDC”, “Black Sabbath”, “Shinedown”]


This snippet will create a string – or list - called “music” with the variables we have specified.

You can join the new list by including an empty space, like so:

>>> print ‘ ’.join(music)


You can also join it by starting code on a new line like:

>>> print “
“.join(music)


There is no right or wrong way, use the method you prefer.

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.