How to print string and int in the same line in Python

This Python tutorial is on how to print string and int in the same line in Python. This is a very common scenario when you need to print string and int value in the same line in Python.

Printing string and integer value in the same line mean that you are trying to concatenate int value with strings.

Some examples:

Hey the value of variabe a is 452
You just entered 845

Etc….

Print string and int in the same line in Python

Here we will see how to concatenate string and int in Python.

In general, if you run this below Python code:

a = 5
print ("the value of a is "+a)

You will get an error like this:

TypeError: can only concatenate str (not “int”) to str



 

Do you know why you are getting an error like this?

Because you are trying to concatenate an integer value with a string using + operator. In Python, the + operator can only concertante strings as Python is a strongly typed programming language.

In order to solve this problem and to achieve our goal to concatenate strings with int we can use these below methods:

Python code to concatenate a string with an int

a = 5
print ("the value of a is "+str(a))

Output:

$ python codespeedy.py
the value of a is 5

Here we have used str() method to convert the int value to int.

There are other techniques too to achieve our goal.

We can also use comma to concatenate strings with int value in Python

a = 5
print ("the value of a is ",a)

Output:

$ python codespeedy.py
the value of a is  5

Concatenate integers in Python

a = 9
b = 7
print(a,b)

Output:

9 7

In this way, we can concatenate two or more integers in Python

Learn,

Leave a Reply

Your email address will not be published. Required fields are marked *