Open In App

How to Print String and Int in the Same Line in Python

Printing both texts and integers on the same line is a common chore for programmers. 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.

Print String and Int in the Same Line in Python

Let’s see the different approaches to solve this problem:



Print String and Int in the Same Line using Concatenation

In this example, we combine the strings “My name is “, name, ” and I am “, and the string representation of age using the + operator.




name = "John"
age = 30
 
print("My name is " + name + " and I am " + str(age) + " years old.")

Output

My name is John and I am 30 years old.


Print String and Int in the Same Line using f-strings

You can directly embed variables and expressions inside f-strings by placing them within curly braces {}. Here’s how you can use f-strings to print strings and integers in the same line:




name = "John"
age = 30
 
print(f"My name is {name} and I am {age} years old.")

Output
My name is John and I am 30 years old.


Print String and Int in the Same Line using format() Method

In this code, we create a template string message with two placeholders {}. We then use the format() method to replace the placeholders with the values of name and age.




name = "John"
age = 30
 
message = "My name is {} and I am {} years old."
formatted_message = message.format(name, age)
 
print(formatted_message)

Output
My name is John and I am 30 years old.


Print String and Int in the Same Line using str.join()

In this code, we use the map() function to convert all elements in the data list to strings, and then we use the join() method to combine them with a space delimiter.




name = "John"
age = 30
 
print("My name is", name, "and I am", age, "years old.")

Output
My name is John and I am 30 years old.



Article Tags :