In this python tutorial, we will discuss how to concatenate strings in python.
How to concatenate strings in python |
We will also discuss on the below topics here
- How to concatenate two strings in python. Can we add two strings in python?
- How to concatenate strings and int in python
- How to concatenate lists in python or join strings python list
- Python concatenate strings in a list
- Python concatenate strings in for loop
- Python concatenate strings in the print statement
- Python concatenate strings with a separator
- Python concatenate strings with space
- Python concatenate strings multiple lines
- Python concatenate strings and numbers
- Python concatenate string and float
- Python concatenate strings and list
- Python concatenate strings and bytes
- Python concatenate strings array
- Python join strings by comma
- Python add string beginning
- Python string add a backslash
- Python string concatenation best practice
- How to concatenate two lists in python
- How to concatenate two dictionaries in python
- How to concatenate dictionaries in python
- How to concatenate string and variable in python
How to concatenate strings in python
Now, let us see how to concatenate strings in python, how to concatenate two strings in python. Can we add two strings in python?
Yes, we can add or concatenate strings. There are multiple ways to concatenate strings. See below for all the approaches.
1- Using + operator
Using + operator is the most common way to concatenate strings in python. You can concatenate two strings using this operator.
The arguments should be string if you are using + operator to concatenate.
Example:
myvar1 = "Python"
myvar2 = "Guides"
# use + operator to concatenate both strings
myvar3 = myvar1 + myvar2
print(myvar3)
The out put will be
PythonGuides
Let’s run the above code and see the output
One important note here is python doesn’t support implicit string conversion. If you try to concatenate a string with a non-string type then it will throw an error
Let’s check this
myvar1 = 3
myvar2 = "Python"
myvar3 = myvar1 + myvar2
print(myvar3)
Output will be an error “TypeError: unsupported operand type(s) for +: ‘int’ and ‘str'”.
myvar3 = myvar1 + myvar2
TypeError: unsupported operand type(s) for +: 'int' and 'str'
See here
2- Using join() method
You can concatenate strings using join() method.
Example:
myvar1 = "Python"
myvar2 = "Guides"
# use join() to concatenate both strings
myvar3 = "".join([myvar1, myvar2])
print(myvar3)
The output will be
PythonGuides
See here
3- Using % Operator
We can also concatenate the strings using % operator
% operator can also be used to format the string.
For example:
myvar1 = "Python"
myvar2 = "Guides"
# use % operator to concatenate both strings
print("% s % s"%(myvar1,myvar2))
In the above example, We have used two %s which shows that myvar1 and myvar2 contains string data type.
The output will be
Python Guides
See here
4- Using format() function
We can also concatenate the strings using format() function. It allows us to concatenate the strings using positional formatting.
{ } (curly braces) are used along with this format() function to position the string. Each string will have one { } (curly braces).
Example:
myvar1 = "Python"
myvar2 = "Guides"
# use format() to concatenate both strings
print("{}{}".format(myvar1, myvar2))
The output will be
PythonGuides
See here
How to concatenate strings and int in python
In Python, We cannot use + operator to concatenate one string and int type. We cannot concatenate a string with a non-string type. It will throw an error “TypeError: unsupported operand type(s) for +: ‘int’ and ‘str'”.
Below are the approaches we can use to concatenate one string and an int type.
1- Using str() function
We can use str() to concatenate one string and an int type.
Example:
myvar1 = "Python"
myvar2 = 3
# use str() to concatenate an int with a string
print(myvar1 + str(myvar2))
The output will be
Python3
See here
2- Using % Operator
We can use % Operator to concatenate one string and an int type.
Example:’
myvar1 = "Python"
myvar2 = 3
# use % operator to concatenate string with int
print("% s % s"%(myvar1,myvar2))
The output will be
Python 3
3- Using format() function
We can use format() function to concatenate one string and an int type.
One more benefit of format() is no need to convert integers into a string before concatenating the data.
Example:
myvar1 = "PythonGuides"
myvar2 = 2020
# use format() to concatenate string with int
print("{}{}".format(myvar1, myvar2))
Output will be
PythonGuides2020
See output here
4- Using f strings
We can use f strings to concatenate one string and an int type.
Note: f strings supports only python 3.6 and above versions.
Example:
myvar1 = "PythonGuides"
myvar2 = 2020
# use format() to concatenate string with int
print(f"{myvar1} {myvar2}")
Output will be
PythonGuides 2020
See the output here
How to concatenate lists in python or How do I combine multiple lists into one python?
There are multiple ways to concatenate multiple lists in python.
1- Using for loop
We can use for loop to concatenate multiple lists in python.
We can traverse the second list and keep appending the elements in the first list using for loop.
Example:
myvar1 = [11, 13, 15, 17, 19]
myvar2 = [23, 25, 27, 29, 31]
# using for loop to concatenate lists
for i in myvar2 :
myvar1.append(i)
# Printing my concatenated list
print("My concatenated list using for loop : "
+ str(myvar1))
The output will be
My concatenated list using for loop : [11, 13, 15, 17, 19, 23, 25, 27, 29, 31]
See the output here
2- Using + operator
You can use + operator to concatenate multiple lists in python.
This is one of the easy and very simple approach to concatenate multiple lists in python.
Example:
myvar1 = [11, 13, 15, 17, 19]
myvar2 = [23, 25, 27, 29, 31]
# using + operator to concatenate lists
myvar3 = myvar1 + myvar2
# Printing my concatenated list
print("My concatenated list using + operator : "
+ str(myvar3))
The output will be
My concatenated list using + operator : [11, 13, 15, 17, 19, 23, 25, 27, 29, 31]
See the output here
3- Using extend() function
You can use extend() to concatenate multiple lists in python.
Example:
mylist1 = [11, 13, 15, 17, 19]
mylist2 = [23, 25, 27, 29, 31]
# using extend() to concatenate lists
mylist1.extend(mylist2)
# Printing my concatenated list
print("My concatenated list using extend() : "
+ str(mylist1))
The output will be
My concatenated list using extend() : [11, 13, 15, 17, 19, 23, 25, 27, 29, 31]
See the output here
4- Using * operator
Using * operator we can also concatenate multiple lists in python.
This operator will work only with python 3.6 and above versions.
Example:
mylist1 = [11, 13, 15, 17, 19]
mylist2 = [23, 25, 27, 29, 31]
# using * operator to concatenate lists
mylist3 = [*mylist1, *mylist2]
# Printing my concatenated list
print("My concatenated list using * operator : "
+ str(mylist3))
The output will be
My concatenated list using * operator : [11, 13, 15, 17, 19, 23, 25, 27, 29, 31]
See here for the output
5- Using list comprehension
We can also concatenate multiple lists using list comprehension.
Example:
mylist1 = [11, 13, 15, 17, 19]
mylist2 = [23, 25, 27, 29, 31]
# using list comprehension to concatenate lists
mylist3 = [b for a in [mylist1, mylist2] for b in a]
# Printing my concatenated list
print("My concatenated list using list comprehension : "
+ str(mylist3))
The output will be
My concatenated list using list comprehension : [11, 13, 15, 17, 19, 23, 25, 27, 29, 31]
See the output here
6- Using itertools.chain() method
We can also concatenate multiple lists itertools.chain() method.
Note: We need to import itertools namespace.
Example:
import itertools
mylist1 = [11, 13, 15, 17, 19]
mylist2 = [23, 25, 27, 29, 31]
# using itertools.chain() method to concatenate lists
mylist3 = list(itertools.chain(mylist1, mylist2))
# Printing my concatenated list
print("My concatenated list using itertools.chain() method : "
+ str(mylist3))
The output will be
My concatenated list using itertools.chain() method : [11, 13, 15, 17, 19, 23, 25, 27, 29, 31]
See the output here
Python concatenate strings in a list
To concatenate strings in a list we will use for loop and the “+ ” operator is the most common way to concatenate strings in a list python.
Example:
l = ['This','is','python']
my_str = ""
for i in l:
my_str += str(i)
str = my_str[0:]
print(my_str)
To get the output, I have used print(my_str). You can refer to the below screenshot for the output.
Python concatenate strings in for loop
Now, let us see how to concatenate strings in for loop
To concatenate strings we will use for loop, and the “+ ” operator is the most common way to concatenate strings in python.
Example:
v = ['Welcome', 'to', 'Python']
my_str = ""
for item in v:
my_str += item
print(my_str)
To get the output, I have used print(my_str). You can refer to the below screenshot for the output.
Python concatenate strings in the print statement
Here, we can see how to concatenate strings in the print statement
To concatenate strings we will use “+ ” operator in the print statement.
Example:
S_name = "Tom"
print ("Welcome" + S_name)
To get the output, I have used (“Welcome” + S_name). You can refer to the below screenshot for the output.
Python concatenate strings with a separator
Now, we will see how to concatenate strings with a separator
We can also concatenate the strings by using the ‘,’ separator in between the two strings, and the “+ ” operator is used to concatenate the string with a comma as a separator.
Example:
s1 = 'Python'
s2 = 'Guides'
str = s1 + ',' + s2
print(str)
To get the output, I have used print(str). You can refer to the below screenshot for the output.
Python concatenate strings with space
Here, we will see how to concatenate strings with space
We can also concatenate the strings by using the space ‘ ‘ in between the two strings, and the “+” operator is used to concatenate the string with space.
Example:
s1 = 'Pizza'
s2 = 'Burger'
str = s1 + ' ' + s2
print(str)
To get the output, I have used print(my_str). You can refer to the below screenshot for the output.
Python concatenate strings multiple lines
Now, we will see python concatenate strings multiple lines
In Python, we can concatenate strings multiple lines by breaking the lines in parentheses. Here, we have used “()” to concatenate string multiple lines.
Example:
my_str = ('Welcome to Python tutorial.'
' Python is one of the most famous language'
' and everyone enjoy coding in python ')
print(my_str)
To get the output, I have used print(my_str). You can refer to the below screenshot for the output.
Python concatenate strings and numbers
Now, we will see how to concatenate strings and numbers
In Python, We cannot use the + operator to concatenate one string and number type. We cannot concatenate a string with a non-string type. We will use str() to convert the number to string type and then it will be concatenated.
Example:
f = 'Pizza'
a = 150
print(f + str(a))
To get the output, I have used print(f + str(a)). You can refer to the below screenshot for the output.
Python concatenate string and float
Let’s see how to concatenate strings and float
In Python, We cannot use the + operator to concatenate one string and float type. We cannot concatenate a string with a non-string type. We will use str() to convert the float to string type and then it will be concatenated.
Example:
s= 'Python'
f = 3.5
c = str(f)
print(s + c)
To get the output, I have used print(s + c). You can refer to the below screenshot for the output.
Python concatenate strings and list
Now, we will see how to concatenate strings and list
To concatenate strings and lists we will use the + operator and the .join() is used to concatenate strings and lists in python.
Example:
l1 = ['Python','C','C++']
my_str = 'I like to code in: '
print(my_str + ','.join(l1))
To get the output, I have used print(my_str + ‘,’.join(l1)). You can refer to the below screenshot for the output.
Python concatenate strings and bytes
Let’s see how to concatenate strings and bytes
To concatenate strings and bytes we will use the + operator to concatenate, and also we use str() to convert the bytes to string type, and then it will be concatenated.
Example:
my_str = 'XXXYYYZZZ '
bytes = b'\xee\xba\xf3\xca'
print(my_str + str(bytes))
To get the output, I have used print(my_str + str(bytes)). You can refer to the below screenshot for the output.
Python concatenate strings array
Let us see how to concatenate strings array
To concatenate strings array we will import numpy as np. Here, a1 and a2 are two strings arrays that will get concatenated using “np.char.add(a1, a2)”.
Example:
import numpy as np
a1 = np.array(['Mango', 'Orange'])
a2 = np.array([' Apple', ' Grapes'])
n_arr = np.char.add(a1, a2)
print(n_arr)
To get the output, I have used print(n_arr). You can refer to the below screenshot for the output.
Python join strings by comma
Now, we will see python join strings by comma
To join strings by comma we will use the comma separator and the join() method as ‘,’.join(my_str).
Example:
my_str = 'Python' 'Guides'
res = ','.join(my_str)
print(res)
To get the output, I have used print(res). You can refer to the below screenshot for the output.
Python add string beginning
Here, we will see python add string beginning
In python, to add string at the beginning we will use for loop to iterate, and it will insert the given string at the beginning of all the items.
Example:
val = [101,102,103]
print(['student{0}'.format(i) for i in val])
To get the output, I have used print([‘student{0}’.format(i) for i in val]). You can refer to the below screenshot for the output.
Python string add a backslash
Let’s see python string add a backslash
In python, to add a backslash in a string we will use “my_str.replace(” ‘ “, “\\’ “)” and then the single backslash will be added to the string.
Example:
my_str = "Python Guide's Tutorial"
res = my_str.replace("'", "\\'")
print(res)
To get the output, I have used print(res). You can refer to the below screenshot for the output.
Python string concatenation best practice
The best practice for string concatenation in Python is by using the simple concatenation + operator. This is because it’s readable and fast. Also, if you are working with two strings then append() can also be the best practice. If you are concatenating a list and string, then the preferred way is to use join() as it makes it more readable.
How to concatenate two dictionaries in python
Here, we will discuss how to concatenate two dictionaries or merging two dictionaries in python.
There are few ways to concatenate two dictionaries in python.
1- Using update() function
We can concatenate two dictionaries in python using update() method.
Example:
mydict1 = {'a': 10, 'b': 8}
mydict2 = {'d': 6, 'c': 4}
# Python code to concatenate dict using update() method
def Merge(mydict1, mydict2):
return (mydict2.update(mydict1))
print(Merge(mydict1, mydict2))
# changes made in dict2
print(mydict2)
The output will be
None
{'d': 6, 'c': 4, 'a': 10, 'b': 8}
See the output here
2- Using ** (double star)
You can concatenate two dictionaries in python using ** (double star).
Example:
mydict1 = {'a': 10, 'b': 8}
mydict2 = {'d': 6, 'c': 4}
def Merge(mydict1, mydict2):
output = {**mydict1, **mydict2}
return output
mydict3 = Merge(mydict1, mydict2)
print(mydict3)
The output will be
{'a': 10, 'b': 8, 'd': 6, 'c': 4}
See the output here