- Concatenate Strings in Python [With Examples]
- How Do You Concatenate Strings in Python?
- Concatenate Strings Over Multiple Lines
- How Do You Concatenate a String to an Int?
- Concatenating a String and a Float
- Concatenate Strings in a For Loop
- Concatenate Strings Using the Python Format Method
- Using the Python Format Method with Positional Arguments
- Using the Python Format Method with Keyword Arguments
- Conclusion
- Python Concatenate String and int, float Variable
- Python concatenate string and variable(int, float, etc)
- 1: Python concatenate strings and int using + operator
- 2: Python concatenate strings and int using str() method
- 3: Python concatenate string and float
Concatenate Strings in Python [With Examples]
Knowing how to concatenate Python strings is something you need when writing your applications. Let’s see the options available to do that.
With Python you can concatenate strings in different ways, the basic one is with the + operator. If you have two strings (string1 and string2) you can concatenate them using the expression string1 + string2. Python also provides the format() method to concatenate multiple strings together.
It’s time for some examples!
How Do You Concatenate Strings in Python?
The first and most basic way to concatenate two or more Python strings is by using the + operator.
For example, let’s define two variables of type string and concatenate them using the + operator.
>>> string1 = "I like" >>> string2 = "Python" >>> string1 + string2 >>> 'I likePython'
We have used the + to concatenate two strings but the result is not exactly what we expected considering that the words like and Python should be separated by a space.
Using the + operator we can also concatenate more than two strings, in this case, we can also concatenate an additional string that contains a single space (” “).
>>> string3 = " " >>> string1 + string3 + string2 'I like Python'
Thinking about it, there’s no point to store a single space in the variable string3, so we can simply write:
>>> string1 + " " + string2 'I like Python'
Concatenate Strings Over Multiple Lines
What if we have a few strings and we want to create a single string that spans across multiple lines?
We can do that by separating the strings with the newline character ( \n ) instead of using a space character as we have done in the previous example:
>>> string1 = "Python modules:" >>> string2 = "Pandas" >>> string3 = "subprocess" >>> string4 = "json" >>> print(string1 + "\n" + string2 + "\n" + string3 + "\n" + string4) Python modules: Pandas subprocess json
You can see that each string is printed at the beginning of a new line.
Let’s say these four strings are inside a list, we could use a for loop to have a similar result:
>>> strings = ["Python modules:", "Pandas", "subprocess", "json"] >>> for string in strings: print(string) Python modules: Pandas subprocess json
In this case, we haven’t specified the newline character in the print statement inside the for loop because the Python print function implicitly adds a newline character at the end of a string.
To remove the implicit newline added at the end of a string by the Python print function you can pass an extra parameter called end.
>>> for string in strings: print(string, end='') Python modules:Pandassubprocessjson
At this point we could include the newline character using the + operator in the same way we have done it before:
>>> for string in strings: print(string + "\n", end='') Python modules: Pandas subprocess json
Obviously, this is just an exercise to learn how the print function and the + operator work.
In a real program you wouldn’t pass the extra “end” parameter and then concatenate the newline character considering that this is something the print function does by default anyway.
Later in this tutorial, you will learn a better way to concatenate the elements of a list of strings into a single string.
How Do You Concatenate a String to an Int?
Now, let’s try to concatenate a string and an integer.
>>> string1 = "Let's concatenate" >>> string2 = "strings" >>> string1 + 3 + string2 Traceback (most recent call last): File "", line 1, in string1 + 3 + string2 TypeError: can only concatenate str (not "int") to str
The Python interpreter raises the TypeError “can only concatenate str (not “int”) to str” because it cannot concatenate a string to an integer.
To concatenate a string to an integer you have to convert the integer into a string using the str() function that returns the string version of a Python object.
>>> string1 + str(3) + string2 "Let's concatenate3strings"
Once again I have forgotten the spaces:
>>> string1 + " " + str(3) + " " + string2 "Let's concatenate 3 strings"
Concatenating a String and a Float
The logic explained for integers in the previous section also applies to other types of numbers, for example floating-point numbers.
If we try to concatenate strings with a float we also get a TypeError back, just with a slightly different error message compared to before: can only concatenate str (not “float”) to str.
>>> string1 + " " + 3.3 + " " + string2 Traceback (most recent call last): File "", line 1, in string1 + " " + 3.3 + " " + string2 TypeError: can only concatenate str (not "float") to str
Once again we can convert the float into a string using the str() function:
>>> string1 + " " + str(3.3) + " " + string2 "Let's concatenate 3.3 strings"
Now you know how to concatenate strings and numbers in Python.
Concatenate Strings in a For Loop
A common scenario is having to create a string from a list also based on specific conditions that have to be met by the elements of the list.
For example, let’s say we have a list of domains and we want to create a string that contains all the domains except two of them.
This is something we would do using a Python for loop:
>>> domains = ["codefather.tech", "amazon.com", "bbc.com", "cnn.com"] >>> skip_domains = ["amazon.com", "bbc.com"] >>> final_domains = "" >>> for domain in domains: if domain not in skip_domains: final_domains += domain + "\n" >>> print(final_domains, end='') codefather.tech cnn.com
The list skip_domains is used to filter out domains we don’t want to include in the final string.
Also notice that to generate the string final_domains we are using the operator += that concatenates what’s on the right side of the equal sign to the existing value of the final_domains string.
Here is an example to clarify this:
>>> final_domains = "codefather.tech\n" >>> final_domains += "cnn.com" + "\n" >>> print(final_domains, end='') codefather.tech cnn.com
The expression using += can also be written as follows:
>>> final_domains = "codefather.tech\n" >>> final_domains = final_domains + "cnn.com" + "\n" >>> print(final_domains, end='') codefather.tech cnn.com
So, the += operator is a more concise way to concatenate strings to an existing string and store the result in the existing string.
Concatenate Strings Using the Python Format Method
The + operator allows to concatenate strings but this doesn’t mean it’s the best way to do string concatenation in Python.
The following example shows why…
Imagine you want to concatenate multiple strings and variables:
>>> first_number = 7 >>> second_number = 3 >>> print("The difference between " + str(first_number) + " and " + str(second_number) + " is " + str(first_number - second_number)) The difference between 7 and 3 is 4
Look at the expression we had to write to print a very simple string.
It’s definitely quite messy…
…it’s also very easy to make mistakes with all the spaces, plus signs and calls to the str() function.
There’s a better way to do this using the string method format().
Look at the official Python documentation above…
We can define a single string and use curly braces <> in the string where we want to specify the value of a variable.
>>> print("The difference between <> and <> is <>".format(first_number, second_number, first_number - second_number)) The difference between 7 and 3 is 4
Using the Python Format Method with Positional Arguments
When using the string format() method we can also specify numeric indexes between curly braces.
These indexes represent positional arguments passed to the format method.
>>> print("The difference between and is ".format(first_number, second_number, first_number - second_number)) The difference between 7 and 3 is 4
The indexes 0, 1, and 2 refer to the first, second, and third parameters passed to the format method.
To show better how this works, let’s swap index 0 and index 2:
>>> print("The difference between and is ".format(first_number, second_number, first_number - second_number)) The difference between 4 and 3 is 7
The values of the first and third variables have been swapped in the final string.
This can also get a bit messy if you have lots of parameters to pass to the format method.
But, there is an even better way…
Using the Python Format Method with Keyword Arguments
The format() method also supports keyword arguments that make the code a lot more readable.
Let’s update the previous example that was using positional arguments. This time we will use keyword arguments instead.
>>> print("The difference between and is ".format(fnum=first_number, snum=second_number, difference=first_number - second_number)) The difference between 7 and 3 is 4
I have assigned keywords to identify the parameters passed to the format method. And I have specified those keywords between curly braces.
Also, I can swap the order in which the parameters are passed to the format method and the output will not change:
>>> print("The difference between and is ".format(snum=second_number, difference=first_number - second_number, fnum=first_number)) The difference between 7 and 3 is 4
Conclusion
With this tutorial, you know pretty much anything you need to concatenate strings in Python.
My suggestion is to get used to the syntax of the format() method and it will make your code a lot cleaner.
Bonus read: in this article, you have learned how to concatenate strings in Python. To complement this knowledge have a look at how to split strings in Python. You will find it very useful in your Python programs!
Related course: build a strong Python foundation with this Python specialization.
I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!
Python Concatenate String and int, float Variable
Python concatenate string and and int, float Variable; In this tutorial, you will learn how to concatenate string and int, float Variable in python.
You must have seen in many programming languages that using the + operator, adding python string and integer, float, etc. But in Python, if you concatenate the string and number with the + operator, the error will occur.
If you add both different data type variables to the + operator in Python and you have not added their data type, then when you run your Python program, an error will occur. We will explain this thing by giving you an example below.
In this python string concatenate/join with other dataTypes variable. Here you will learn how to concatenate strings and int, how to concatenate strings and float and etc.
Python concatenate string and variable(int, float, etc)
- 1: Python concatenate strings and int using + operator
- 2: Python concatenate strings and int using str() method
- 3: Python concatenate string and float
1: Python concatenate strings and int using + operator
Let’s show you that if you concatenate strings and int (integer) with the + operator in Python. So which error will come:
Example 1: Python Program to Concatenate Strings and integer using + operator
str = 'Current year is ' y = 2020 print(str + y)
Traceback (most recent call last): File "/Users/dell/Documents/Python-3/basic_examples/strings/string_concat_int.py", line 5, in print(str + y) TypeError: can only concatenate str (not "int") to str
You must have seen in the python program given above that you cannot add string and int to python by using the + operator.
Note:- If you want to associate the integer number with the string, you will have to convert it to a string first.
You have to use the str() method to convert the number into string dataType in Python.
2: Python concatenate strings and int using str() method
Now you will see that the first python program was created. The error that was coming in will not come now.
Why the python variable we had earlier in this python program was the integer value. Using the Python str() method, convert it to string and then concatenate string variable and integer variable into python.
Example 2: Python Program to Concatenate Strings and integer using str()
string = 'Current year is ' y = 2020 z = str(y) print(string + z))
3: Python concatenate string and float
Why the variable we had earlier in this python program was the float value. Using the Python str() method, convert it to string and then concatenate string variable and float variable into python:
Example 3: Python Program to Concatenate Strings and float using str()
string = 'This is float number ' a = 8.5 b = str(a) print(string + b)