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,

4 responses to “How to print string and int in the same line in Python”

  1. naveen says:

    how to print a string and integer with user input in pythn

  2. Noel Springer says:

    Hi. Excellent article!

    Just one small typo. Under the heading “Python code to concatenate a string with an int” > “Output” is the line:

    “Here we have used str() method to convert the int value to int.” Which should read:

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

    Cheers

  3. Dave Eger says:

    Have searched everywhere and cannot find how to print on one line, a string and a math calculation……
    ie:
    a = 5
    b = 7
    print(“this is an addition adding 5 and 7: ” + a+b). This returned an error. I am looking for output:
    this is an addition adding 5 and 7: 12

Leave a Reply

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