# 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.

💬 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 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!

## 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.

## 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.

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!')```

## 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.

💡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!

## 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.

💡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 > f_solved 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.

## 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

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

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

This code reads in a fictitious `finxter_top5.csv` file.

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)`. 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} {row}`). Then, the `solved` variable is formatted to display commas (`,`) indicating thousands (`{row:,d}`). The results are saved to `e_body` and, for this example, are output to the terminal.

For this example, the first record displays.

🧩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!