There are times when you want to be able to print the contents of a variable along with a string to help provide some context around what has been output to the console. So how can you print both a string and a variable in Python?
The three methods of being able to print a string and a variable together in Python is by using: string concatenation (using
+
), or using the
.format()
string method, or using f-strings.
Let’s explore each of these approaches in a little more detail to see which approach best suits your requirements and needs.
How To Concatenate Strings
To print a string with a variable the first method most people come across is using the concatenation approach.
This is perhaps the
easiest to understand
as all it involves just remembering one thing:
the
+
sign
.
Here’s how this approach works:
>>> x = "Hello"
>>> phrase = x + " world!"
>>> print(phrase)
Hello world!
As you can see from the above example using the simple
+
operator in a string concatenates two elements into one string.
String concatenation works well with the
+
operator sign, however, this assumes that both types of what is being concatenated are of the same data type. In the example above both the
x
and the string
" world!"
are
string
data types.
If
x
were a different data type, such as an
integer
data type, you would get a
TypeError
when trying to perform this type of concatenation technique:
>>> x = 100
>>> phrase = x + " world!"
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
As you can see the REPL console is showing on that last line that for the operand
+
it is unsupported when one data type is
int
and the other is
str
.
To get around this problem, simply convert the
int
data type to a string by using the built-in
str()
method, like so:
>>> x = 100
>>> phrase = str(x) + " world!"
>>> print(phrase)
100 world!
While this method is easy, there’s an even easier way if you’re looking to append strings to an existing variable.
Append To End Of String
Another way of using the
+
operator with the concatenation strings in Python is the assignment operator
+=
. While this approach is more popular with
incrementing in Python
, it can easily be used with strings and is most helpful when the need for concatenating strings occurs on a variable, and the addition of the new string needs to be added to the end of the existing string.
Here’s an example demonstrating this technique:
>>> x = "Add"
>>> x += " strings"
>>> x += " together"
>>> print(x)
Add strings together
Notice how in the above example I concatenate two additional strings to the original string
x
which started with
"Add"
.
While this approach is fantastic when appending strings to the end of an already existing string variable, what if your variable strings needs to be inserted inside another string?
Insert String Inside Another String
What if you need to insert a string into another string can you still use the assignment operator
+=
?
Using the
+=
may not be the best technique as its best use case is when you want to add something to the
end of a string
, if you’re looking to insert a string inside another string you could the
+
operator provided the structure of what needs to be inserted is set up correctly.
For example, if you wanted to insert a value between
<strong>
HTML tags you could achieve the result by doing something like this:
>>> strong_value = "I am strong!"
>>> html_tags = "<strong>" + strong_value + "</strong>"
>>> print(html_tags)
<strong>I am strong!</strong>
As you can see from the above code you insert a string
within
other strings using the
+
operator. However, this type of use case is best when dealing with smaller strings. If you have to insert strings within larger strings, like you would with a mail merge client on a template form, then this process becomes quite tedious to do.
Thankfully, Python provides additional techniques to be able to insert strings into larger strings.
How To Use
.format()
String Method
A technique to help manage the insertion of strings into other strings without increasing the complexity of what is trying to be done is to use the
.format()
string method
.
An example of using this string method can be demonstrated simply below:
>>> "I am {} years old".format(44)
'I am 44 years old'
As you can see from the above example the curly braces
{}
are used as the insertion point for the value placed within the parameter of the
.format()
method.
But what if you have to insert more than one variable into a string?
Insert More Than One Variable Into A String
You can use the
.format()
method to insert more than one variable into a string, but to accomplish this you need to insert additional parameters into your
.format()
method.
Here’s a demonstration of how this can be done:
>>> "My name is {} and I live in {}".format("Ryan", "Sydney")
'My name is Ryan and I live in Sydney'
As you can see from the above example I have inserted more placeholders
{}
into the original string and Python knows that each subsequent value inserted into the parameters related positionally to each placeholder in the original string.
Therefore, the first placeholder relates to the first parameter, the second placeholder pertains to the second parameter inserted into the
.format()
method and so on.
But what if I have multiple placeholders which contain all the same references?
If there are
more placeholders
than values inserted into the
.format()
string method you will get an
IndexError
if your code resembles something like this:
>>> "My name is {} and people call me {}".format("Ryan")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: Replacement index 1 out of range for positional args tuple
In the above example, I have 2 placeholders for text, but I have only 1 parameter inserted into the
.format()
string method. As a result Python returns an
IndexError
informing me that the index 1 is out of range – in other words it had no problems inserting
Ryan
into the
first placeholder
, but had great difficulty finding a value for the second placeholder as there is no second parameter into the arguments of
.format()
.
So what can you do?
Typing
"Ryan"
multiple times into the
.format()
method would get very old very quickly. There has to be an easier way.
And there is!
To make your code work you need to insert the index reference according to the parameter being referenced.
Here’s how to make the above code work, see if you can spot the differences:
>>> "My name is {0} and people call me {0}".format("Ryan")
'My name is Ryan and people call me Ryan'
As you can see the index reference inserted inside the placeholders is the number
0
which relates to the one and only parameter inserted into the
.format()
string method.
This enables you to reference parameters inserted into the
.format()
method according to their index position.
For example, here is how you can use the
.format()
string method to insert multiple strings:
>>> "My name is {0}, I am {1} years old and people call me {0}. I live in {2}.".format("Ryan", 44, "Sydney")
'My name is Ryan, I am 44 years old and people call me Ryan. I live in Sydney.'
Notice how each reference needs its index position to be able to be inserted into the original string.
However, this does get quite cumbersome the more variables you want to insert and keeping track can get complicated. There is one more approach that you can use and is known as the f-strings.
How To Use f-Strings
Since Python 3.6 another way of being able to insert strings into another string is to use Python’s f-strings. The way f-strings work is similar to the
.format()
string method, but instead of appending the strings to insert at the end of the string in the
format()
parameters.
f-strings enable the use of being able to write your variable insertions into the original string by using placeholders where the placeholders contain the name of the variables to be inserted directly.
Here is a demonstration of their use:
>>> my_name = "Ryan"
>>> my_age = 44
>>> my_city = "Sydney"
>>> f"My name is {my_name}, I am {my_age} years old and people call me {my_name}. I live in {my_city}."
'My name is Ryan, I am 44 years old and people call me Ryan. I live in Sydney.'
As you can see from the above example the reason why this technique is called f-strings is that before entering the quotes for your string you need to prefix it with the letter
f
. Then inside the string each insertion point is like the previous
format()
method by using the curly braces
{}
with the only difference being instead of index numbers inside there are variable names.
If you happen to reference a variable name that doesn’t exist you will get a
NameError
informing you of the variable used in your string that is not defined.
Summary
There are several techniques in Python to insert a variable into a string. The most common approach is to use the
+
operator and to concatenate strings together, this can give rise to using the assignment operator should strings and/or variables be appended to each other.
The other techniques are somewhat the same and one involves the
.format()
string method whereas the other is a more recent development in Python and involves f-strings. Both of these techniques use curly braces to insert variables into the original string with the former method using index references according to where a variable has been inserted into the parameters, whereas the other relies on the variable already being defined and using its variable name.
Your approach to using a particular technique will depend on which method best suits your use case and makes your code easy to understand.