How to Print a String and an Integer

5/5 - (2 votes)

Problem Formulation and Solution Overview

In this article, you’ll learn how to print a string and an integer together in Python.

To make it more fun, we have the following running scenario:

The Finxter Academy has decided to send its users an encouraging message using their First Name (a String) and Problems Solved (an Integer). They have provided you with five (5) fictitious users to work with and to select the most appropriate option.

First_NamePuzzles Solved
Steve39915
Amy31001
Peter29675
Marcus24150
Alice23580

💬 Question: How would we write code to print a String and an Integer?

We can accomplish this task by one of the following options:

  • Method 1: Use a print() function
  • Method 2: Use the print() function and str() method
  • Method 3: Use f-string with the print() function
  • Method 4: Use the %d, %s and %f operators
  • Method 5: Use identification numbers
  • Method 6: Use f-string conditionals
  • Bonus: Format CSV for output

Method 1: Use the print() function

This example uses the print() function to output a String and an Integer.

print('Steve', 39915)

This function offers the ability to accept various Data Types and output the results, separated by commas (,) to the terminal.

Although not the most aesthetically pleasing output, it gets the job done. The print() function at its most simplistic level!

Steve 39915
Python Print Function [And Its SECRET Separator & End Arguments]

Method 2: Use the print() function and str() method

This example uses the print() function and the str() method to format and output a sentence containing a String and an Integer.

print('Steve has solved ' + str(39915) + ' puzzles!')

To successfully output the contents of the print() function, the Integer must first be converted to a String. This can be done by calling the str() method and passing, in this case, 39915 as an argument.

Steve has solved 39915 puzzles!
Python str() Function

Method 3: Use f-string with print() function

This example uses the f-string inside the print() function. This method uses curly brackets ({}) to accept and display the data.

first_name = 'Steve'
solved = 39915
print(f'{first_name} has solved {solved} puzzles to date!')

Above, two (2) variables are declared: first_name and solved.

The print() function is called and passed these two (2) variables, each inside curly braces ({}). This indicates that Python should expect two (2) variables of unknown Data Types. The print() function executes and sends this output to the terminal.

Steve has solved 39915 puzzles!
Python format() Function: No-BS Guide by Example

What if you need to print out all Finxter users? This example assumes the data is saved to separate Lists and output using a For loop.

f_name = ['Steve', 'Amy', 'Peter', 'Marcus', 'Alice']
f_solved = [39915, 31001, 29675, 24150, 23580]

for i in range(len(f_name)):
    print(f'{f_name[i]} has solved {f_solved[i]} puzzles to date!')
Steve has solved 39915 puzzles to date!
Amy has solved 31001 puzzles to date!
Peter has solved 29675 puzzles to date!
Marcus has solved 24150 puzzles to date!
Alice has solved 23580 puzzles to date!
A Surprising Python Trick: Loop ... Else?!

Method 4: Use %d, %s and %f Operator

This examples uses the %d (decimal value), the %s (string value), and %f (float value) inside the print() function to output the fictitious Finxter user’s data.

f_name = ['Steve', 'Amy', 'Peter', 'Marcus', 'Alice']
f_solved = [39915, 31001, 29675, 24150, 23580]
f_avg  = [99.315, 82.678, 79.563, 75.899, 71.233]

i = 0
while i < len(f_name):
    print("%s solved %d puzzles with an average of %3.2f." % (f_name[i], f_solved[i], f_avg[i]))
    i += 1

Above, three (3) Lists are declared. Each List carries different information for each user (f_name, f_solved, f_avg).

The following line instantiates a while loop and a counter (i) which increments upon each iteration. This loop iterates until the final element in f_name is reached.

Inside the loop, the %s (accepts strings) is replaced with the value of f_name[i]. Then, %d (accepts integers) is replaced with the value of f_solved[i]. Finally, the %3.2f (for floats) value of is replaced with f_avg[i] having two (2) decimal places. The output displays below.

Steve solved 39915 puzzles with an average of 99.31.
Amy solved 31001 puzzles with an average of 82.68.
Peter solved 29675 puzzles with an average of 79.56.
Marcus solved 24150 puzzles with an average of 75.90.
Alice solved 23580 puzzles with an average of 71.23.

💡Note: In the %3.2f annotation, the value of three (3) indicates the width, and 2 indicates the number of decimal places. Try different widths!

How to Create a Python List?

Method 5: Use identification numbers

This example uses field identification numbers, such as 0, 1, 2, etc., inside the print() function to identify the fields to display and in what order.

f_name = ['Steve', 'Amy', 'Peter', 'Marcus', 'Alice']
f_solved = [39915, 31001, 29675, 24150, 23580]

for i in range(len(f_name)):
    print('{0} solved {1} puzzles!'.format(f_name[i], (format(f_solved[i], ',d'))))

Above, two (2) Lists are declared. Each List carries different information for each Finxter user (f_name, f_solved).

Then, using a For loop, the code runs through the above Lists. The numbers wrapped inside curly braces ({0}, {1}) indicate holding places for the expected data. This data appears inside the format() function ((format(f_solved[i], ',d')))) and are output to the terminal.

Steve solved 39,915 puzzles!
Amy solved 31,001 puzzles!
Peter solved 29,675 puzzles!
Marcus solved 24,150 puzzles!
Alice solved 23,580 puzzles!

💡Note: The data in f_solved is formatted to display a thousand comma (',d').

Method 6: Use f-string and a conditional

This example uses an f-string and a conditional to display the results based on a condition inside the print() function.

f_name = ['Steve', 'Amy', 'Peter', 'Marcus', 'Alice']
f_solved = [39915, 31001, 29675, 24150, 23580]
print(f'Has Alice solved more puzzles than Amy? {True if f_solved[4] > f_solved[1] else False}')

Above, two (2) Lists are declared. Each List carries different information for each Finxter user (f_name, f_solved).

Inside the print() function, the code inside the curly braces ({}) checks to see if the number of puzzles Alice has solved is greater than the number of puzzles Amy has solved. True or False returns based on the outcome and is output along with the String to the terminal.

Has Alice solved more puzzles than Amy? False

Bonus: Putting it Together!

This article used several ways to format a String and an Integer. However, let’s put this together to generate a custom email body!

The first step is to install the Pandas library. Click here for installation instructions.

import pandas as pd

finxters = pd.read_csv('finxter_top5.csv')

for _, row in finxters.iterrows():
    user_email = row[3]

    e_body = f"""
    Hello {row[0]} {row[1]},\n
    The Finxter Academy wants to congratulate you on solving {row[2]:,d} puzzles.
    For achieving this, our Team is sending you a free copy of our latest book!
    Thank you for joining us.
    The Finxter Academy
    """
    print(e_body.strip())

This code reads in a fictitious finxter_top5.csv file.

First_NameLast_NameSolvedEmail
0SteveHamilton39915steveh@acme.org
1AmyPullister31001amy.p@bminc.de
2PeterDunn29675pdunn@tsce.ca
3MarcusWilliams24150marwil@harpoprod.com
4AliceMiller23580amiller@harvest.com

Next, a For loop is instantiated to iterate through each row of the DataFrame finxters.

💡Note: The underscore (_) character in the for loop indicates that the value is unimportant and not used, but needed.

For each loop, the user’s email address is retrieved from the row position (row[3]). This email address saves to user_email.

Next, the custom email body is formatted using the f-string and passed the user’s First Name and Last Name in the salutation ({row[0]} {row[1]}). Then, the solved variable is formatted to display commas (,) indicating thousands ({row[2]:,d}). The results are saved to e_body and, for this example, are output to the terminal.

For this example, the first record displays.

Hello Steve Hamilton,
The Finxter Academy wants to congratulate you on solving 39,915 puzzles. For achieving this, our Team is sending you a free copy of our latest book. Thank you for joining us. The Finxter Academy

🧩A Finxter Challenge!
Combine the knowledge you learned here to create a custom emailer.
Click here for a tutorial to get you started!


Summary

These six (6) methods of printing Strings and Integers should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!


Programming Humor