Python Concatenate String and Variable (int float)

Python concatenate/join string and variable like int, float; Through this tutorial, i am going to show you how to concatenate string and other dataTypes variable int, float, 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

See the following program to concatenate string and int (integer) with the + operator in Python:

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

Using the str() method to concatenate strings to int or integer:

string = 'Current year is '
y = 2020
z = str(y)
print(string + z))

Output

Current year is 2020

3: Python concatenate string and float

Using the Python str() method, convert it to string and then concatenate string variable and float variable into python:

string = 'This is float number '
a = 8.5
b = str(a)
print(string + b)

Output

This is float number 8.5

Recommended Python Tutorials

Recommended:-Python Lists
Recommended:-Python Strings

Leave a Comment