How to print a variable and a String on the same line in Python

When working with multiple strings or variables and the need arises to combine their data into a single variable, list, array, or any other data structure, we refer to this process as data concatenation. Python offers various methods to achieve this, allowing you to combine string and integer variables and print them on the same line. In this article, we will learn how to print a variable and a string together on the same line in Python. Specifically, we will focus on the concatenation of strings with integers. If you want to learn more about Python Programming, visit Python Programming Tutorials.

Print a Variable and a String on the same Line in Python

In Python, there are several methods to print a variable and a string on the same line. First, you can use the + operator along with the str() function to concatenate a string and a variable, allowing you to print them together. Another approach is to use the .format() method, where you can insert the variable within a string using curly braces {} and then use the .format() method to replace them with the variable’s value. Additionally, you can use the % operator to achieve the same result, by specifying the variable as a tuple alongside the string using the % formatting. Lastly, Python 3.6 introduced the f-string method, which allows you to directly insert variables within a string by prefixing it with an ‘f’ character, simplifying the process of printing strings and variables on the same line.

Use + str() to Print a String and variable on the same line

The + operator can be used for the concatenation of a string with integer. However, when you need to concatenate an integer with a string, you first need to convert the integer into a string using the str() function. Consider an example code that counts the items bought from a market and displays them using string concatenation with the str() function:

# Initialize a variable to keep track of the number of items
item_count = 0

# Create an empty list to store the items
items = []

# Start a loop that continues until 'done' is entered
while True:

    # Ask the user to enter an item
    item = input("Enter the item bought (or 'done' to finish): ")

    # Check if the user entered 'done'. If yes then exit the loop
    if item.lower() == 'done':
        break

    # Add the item to the list
    items.append(item)

    # Increment the item count
    item_count += 1

# Iterate over the range of item count and display the item number and the corresponding item
print("You bought the following items:")

for i in range(item_count):

    print(str(i+1) + ". " + items[i])

Output:

Enter the item bought (or 'done' to finish): apples
Enter the item bought (or 'done' to finish): gauva
Enter the item bought (or 'done' to finish): oranges
Enter the item bought (or 'done' to finish): done
You bought the following items:
1. apples
2. gauva
3. oranges

In this code, a while loop is used to repeatedly ask the user to enter the items they bought from the market. The loop continues until the user enters ‘done’ to indicate that they have finished. Each item entered by the user is added to the items list, and the item_count variable is incremented. After the loop ends, the code displays the list of items using string concatenation with the str() function. The items are displayed in a numbered format, indicating the order in which they were entered.

Note that the str(i+1) expression is used to convert the item number (0-indexed) to a string, and the + operator is used for string concatenation.

Please note that this is a basic example and does not include error handling or input validation.

Printing String and variable on the same line using .format(str())

Another way to concatenate a string and an input integer variable is by using the format() method. In this method, you define a placeholder in the string using curly brackets {}. Then, you can pass the input value to the format() method, which will insert that value into the string’s placeholder. Data concatenation is commonly used when you want to display a predefined message along with a user’s input. For example, let’s say you want to ask the user for their name and then display a personalized greeting. You can achieve this by concatenating the user’s input with a predefined message using the format operator.

Let’s look at another example. The program prompts the user to enter the name of the fruit they want to buy and the quantity. Based on the entered fruit name, the corresponding cost is determined. The code then calculates the total cost by multiplying the cost per fruit with the quantity. Finally, it uses the format() method to concatenate the quantity, product, and total cost into the invoice string, which is then printed to display the final message.

print("Welcome to the Grocery store!")

product = input("Enter the name of the fruit you want to buy (Apple/Mango/Banana/Kiwi): ").lower()

if product == 'apple':
    cost = 20
elif product == 'mango':
    cost = 30
elif product == 'banana':
    cost = 10
elif product == 'kiwi':
    cost = 25
else:
    print("Sorry, we don't have that fruit available.")
    exit()

quantity = int(input("Enter the quantity you want to buy: "))

total_cost = cost * quantity

invoice = "You have purchased {} {}(s). The total cost is Rs. {}.".format(quantity, product, total_cost)

print(invoice)
Output: 
Welcome to the Grocery store!
Enter the name of the fruit you want to buy (Apple/Mango/Banana/Kiwi): kiwi
Enter the quantity you want to buy: 3
You have purchased 3 kiwi(s). The total cost is Rs. 75.

The .format() the method allows you to insert the values of variables (quantity, product, total_cost) into the string invoice by using curly brackets {} as placeholders. The values are passed to format() in the order they appear in the string. The resulting formatted string is then printed.

Use % for Printing a String and a variable on the same line

The % operator in Python is used for string formatting and can be used to concatenate an integer and a string. By placing a %s placeholder within the string, we can substitute it with the corresponding integer value. This functionality comes in handy when building URLs that require numeric parameters. String formatting allows us to dynamically generate URLs with specific numeric values based on the context of our program. Let’s consider an example that demonstrates how to use the % operator.

# Using '%' operator to concatenate an integer with a string
page_id = 2
url_template = "https://www.entechin.com/page?id=%s"
url = url_template % page_id

print(url)
Output:
https://www.entechin.com/page?id=2

In this example, we have a variable page_id with a value of 2. The variable url_template holds the url of a website i.e. "https://www.entechin.com/page?id=%s“, where %s acts as a placeholder for the integer value. The line url = url_template % page_id substitutes the %s placeholder with the value of page_id and assigns the resulting URL to the variable url.

Naming images in a specific format can be helpful for training machine learning models. It ensures that the images have a standardized naming convention, making it easier to preprocess and feed them into the model. By including numbers in the file names, you can easily identify the order of the images. This is particularly useful when dealing with large datasets or when you need to process the images in a specific order. For example, when creating file names for a large image dataset.

import os

# Specify the base path
base_path = "/path/to/images/"

# Specify the number of images
num_images = 100

# Iterate over the range of image numbers
for i in range(1, num_images + 1):

    # Generate the file name by concatenating the base path with the image number and file extension
    filename = os.path.join(base_path, "image_%d.jpg" % i)
    
    # display file name for demonstration purposes
    print(filename)  

In this example, the code starts by specifying the base path where the images are located. You can modify base_path to the desired directory path where your images are stored. Inside the loop, the os.path.join() function is used to concatenate the base path with the image file name to form the complete file path. By using the % operator with the %d format specifier, we can insert a number ‘i‘ into the file name template which represents the image index or identifier. Finally, you can perform further processing with the generated file name, such as saving the image or performing other operations specific to your use case.

Note that you can adjust the base file name, the range of image numbers, and the file extension (e.g., ".jpg") based on your specific requirements.

Concatenate strings with integers using the F-string method

The last but not the least is to use the f-string method. The ‘f’ or ‘F’ is used as a prefix before the string. It tells the Python compiler to evaluate the expressions inside curly braces {} and substitute them with their corresponding values if they exist. This method provides a concise and readable way to concatenate strings with variables.

Let’s consider an example where you ask the user to input their roll number. You want to display the message “My Roll Number is 23”, where 23 is an integer obtained from the user input. The following example illustrates the concatenation process:

# Using f-string method for data concatenation

roll_number = int(input("Enter your roll number: "))
print(f"My Roll Number is {roll_number}")

Output:

Enter your roll number: 125
My Roll Number is 125

Consider another example in which you have multiple inputs i.e., name and roll number.

name = input("Enter your name: ")
roll_number = int(input("Enter your roll number: "))
print(f"My name is {name} and my Roll Number is {roll_number}.")
Enter your name: Ali
Enter your roll number: 12
My name is Ali and my Roll Number is 12.

In this code, the input() function is used to prompt the user to enter their name, and the entered value is stored in the name variable. Next, the input() the function is used again to prompt the user to enter their roll number. The entered value is converted to an integer using int() and stored in the roll_number variable.

Finally, the f-string {} placeholders are used to insert the values of name and roll_number into the string. The f prefix before the string indicates that it is an f-string. The expressions inside the curly braces {} are evaluated and replaced with the actual values of name and roll_number.

Conclusion

The string concatenation with integers allows us to create more meaningful and dynamic output by incorporating numeric values within the textual context. String concatenation with integers is commonly used in scenarios such as displaying formatted output or messages, building file names, or creating dynamic queries or requests that include numerical data. In this article, we have learned different ways of concatenating strings with integers. You have also observed how different applications utilize data concatenation and how string concatenation techniques can be applied to them.

By concatenating strings and integers, we can create strings that provide relevant information or incorporate numeric values in a meaningful way for various purposes, including user interaction, data processing, and output generation.

For any queries, contact us.

Leave a Comment

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