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)
Python is whatever variable you want to concatenate/join with the python string. That python variable can be anything like a variable can be an integer, a variable can be of float type, 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)
Output
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))
Output
Current year is 2020
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)
Output
This is float number 8.5