Print string and integer in the same line in Python

In this tutorial, we are Printing both texts and integers on the same line. Python, fortunately, has various methods for accomplishing this, making it simple to display a combination of text and numerical values in your output. In this article, we’ll explore various ways to print strings and integers in the same line in Python

Methods to Print texts and integers in same line:

  1. Using concatenation and ‘str()’ method
  2. Using fString
  3. Using ‘format()’ method

Method 1: Using str() Method on Integer and Concatenation

In this method, we convert the integer to a string using the str() function and then concatenate it with other strings.

name = "Abhishek"
age= 20
print("Hi, My name is " + name + " and my age is " + str(age))

Break-down of the code:

  • The ‘str()’ function converts the integer age to a string.
  • Concatenation (‘+’ operator) is used to join the strings together.
  • This method is straightforward to understand.

Output:

Hi, My name is Abhishek and my age is 20

Method 2: Using f-Strings

Python 3.6 introduced f-strings, which provide a more readable and concise way to format strings.

Code:

name = "Abhishek"
age= 20
print(f"Hi, My name is {name} and my age is {age}")

Break-down of the code:

  • ‘f-Strings’ are prefixed with an f and use curly braces ‘{}’ to embed expressions.
  • This method is more readable and concise compared to using ‘str()’ and concatenation.
  • ‘f-Strings’ can handle various data types without explicit conversion.

Output:

Hi, My name is Abhishek and my age is 20

Method 3: Using the ‘format()’ Method

The ‘format()’ method allows you to format strings by placing placeholders ‘{}’ in the string and passing the values to be inserted.

name = "Abhishek" 
age= 20
lineToPrint = "Hi, My name is {} and my age is {}"
format_text = lineToPrint.format(name,age)
print(format_text)

Break-down of the code:

  • The ‘format()’ method inserts the values of ‘name’ and ‘age’ into the placeholders ‘{}’.
  • This method is flexible and allows for more complex string formatting.
  • It’s a good alternative for versions of Python before 3.6.

Output:

Hi, My name is Abhishek and my age is 20

Leave a Comment

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

Scroll to Top