08-25-2022, 10:37 AM
How to Print a String and an Integer
5/5 – (1 vote)
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_Name |
Puzzles Solved
Steve |
39915
Amy |
31001
Peter |
29675
Marcus |
24150
Alice |
23580
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 function to output a String and an Integer.
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 function at its most simplistic level!
Steve 39915
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyXhEvg8Domk%2Fhqdefault.jpg)
Method 2: Use the print() function and str() method
This example uses the function and the method to format and output a sentence containing a String and an Integer.
To successfully output the contents of the function, the Integer must first be converted to a String. This can be done by calling the method and passing, in this case, as an argument.
Steve has solved 39915 puzzles!
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4MdBRgQOkqc%2Fhqdefault.jpg)
Method 3: Use f-string with print() function
This example uses the inside the function. This method uses curly brackets () to accept and display the data.
Above, two (2) variables are declared: and .
The 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 function executes and sends this output to the terminal.
Steve has solved 39915 puzzles!
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyWky-3tvyRY%2Fhqdefault.jpg)
What if you need to print out all Finxter users? This example assumes the data is saved to separate and output using a loop.
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!
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fjk6JTGAmXJE%2Fhqdefault.jpg)
Method 4: Use %d, %s and %f Operator
This examples uses the (decimal value), the (string value), and (float value) inside the function to output the fictitious Finxter user’s data.
Above, three (3) Lists are declared. Each List carries different information for each user (, , ).
The following line instantiates a loop and a counter (i) which increments upon each iteration. This loop iterates until the final element in is reached.
Inside the loop, the (accepts strings) is replaced with the value of . Then, (accepts integers) is replaced with the value of . Finally, the %3.2f (for floats) value of is replaced with 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 annotation, the value of three (3) indicates the width, and 2 indicates the number of decimal places. Try different widths!
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqXOFngx0bQU%2Fhqdefault.jpg)
Method 5: Use identification numbers
This example uses field identification numbers, such as 0, 1, 2, etc., inside the function to identify the fields to display and in what order.
Above, two (2) are declared. Each carries different information for each Finxter user (, ).
Then, using a loop, the code runs through the above . The numbers wrapped inside curly braces () indicate holding places for the expected data. This data appears inside the function () 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 is formatted to display a thousand comma ().
Method 6: Use f-string and a conditional
This example uses an and a conditional to display the results based on a condition inside the function.
Above, two (2) Lists are declared. Each carries different information for each Finxter user (, ).
Inside the 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.
This code reads in a fictitious file.
|
First_Name |
Last_Name |
Solved |
Email
0 |
Steve |
Hamilton |
39915 |
steveh@acme.org
1 |
Amy |
Pullister |
31001 |
amy.p@bminc.de
2 |
Peter |
Dunn |
29675 |
pdunn@tsce.ca
3 |
Marcus |
Williams |
24150 |
marwil@harpoprod.com
4 |
Alice |
Miller |
23580 |
amiller@harvest.com
Next, a For loop is instantiated to iterate through each row of the DataFrame.
Note: The underscore () character in the 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 (. This email address saves to .
Next, the custom email body is formatted using the and passed the user’s First Name and Last Name in the salutation (). Then, the variable is formatted to display commas () indicating thousands (). The results are saved to 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
5/5 – (1 vote)
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_Name |
Puzzles Solved
Steve |
39915
Amy |
31001
Peter |
29675
Marcus |
24150
Alice |
23580
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 functionCode:
print()
- Method 2: Use the function andCode:
print()methodCode:str()
- Method 3: Use with theCode:
f-stringfunctionCode:print()
- Method 4: Use the ,Code:
%dandCode:%soperatorsCode:%f
- Method 5: Use identification numbers
- Method 6: Use conditionalsCode:
f-string
- Bonus: Format CSV for output
Method 1: Use the print() function
This example uses the
Code:
print()Code:
print('Steve', 39915)This function offers the ability to accept various Data Types and output the results, separated by commas (
Code:
,Although not the most aesthetically pleasing output, it gets the job done. The
Code:
print()Steve 39915
Method 2: Use the print() function and str() method
This example uses the
Code:
print()Code:
str()Code:
print('Steve has solved ' + str(39915) + ' puzzles!')To successfully output the contents of the
Code:
print()Code:
str()Code:
39915Steve has solved 39915 puzzles!
Method 3: Use f-string with print() function
This example uses the
Code:
f-stringCode:
print()Code:
{}Code:
first_name = 'Steve'
solved = 39915
print(f'{first_name} has solved {solved} puzzles to date!')Above, two (2) variables are declared:
Code:
first_nameCode:
solvedThe
Code:
print()Code:
{})Code:
print()Steve has solved 39915 puzzles!
What if you need to print out all Finxter users? This example assumes the data is saved to separate
Code:
ListsCode:
ForCode:
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!
Method 4: Use %d, %s and %f Operator
This examples uses the
Code:
%dCode:
%sCode:
%fCode:
print()Code:
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 += 1Above, three (3) Lists are declared. Each List carries different information for each user (
Code:
f_nameCode:
f_solvedCode:
f_avgThe following line instantiates a
Code:
whileCode:
f_nameInside the loop, the
Code:
%sCode:
f_name[i]Code:
%dCode:
f_solved[i]Code:
f_avg[i]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 Code:
%3.2fMethod 5: Use identification numbers
This example uses field identification numbers, such as 0, 1, 2, etc., inside the
Code:
print()Code:
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)
Code:
ListsCode:
ListCode:
f_nameCode:
f_solvedThen, using a
Code:
ForCode:
ListsCode:
{0}, {1}Code:
format()Code:
(format(f_solved[i], ',d')))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 Code:
f_solvedCode:
',d'Method 6: Use f-string and a conditional
This example uses an
Code:
f-stringCode:
print()Code:
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
Code:
ListCode:
f_nameCode:
f_solvedInside the
Code:
print()Code:
{}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.
Code:
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
Code:
finxter_top5.csv|
First_Name |
Last_Name |
Solved |
0 |
Steve |
Hamilton |
39915 |
steveh@acme.org
1 |
Amy |
Pullister |
31001 |
amy.p@bminc.de
2 |
Peter |
Dunn |
29675 |
pdunn@tsce.ca
3 |
Marcus |
Williams |
24150 |
marwil@harpoprod.com
4 |
Alice |
Miller |
23580 |
amiller@harvest.com
Next, a For loop is instantiated to iterate through each row of the DataFrame
Code:
finxters
Note: The underscore (Code:
_Code:
forFor each loop, the user’s email address is retrieved from the row position (
Code:
row[3])Code:
user_emailNext, the custom email body is formatted using the
Code:
f-stringCode:
{row[0]} {row[1]}Code:
solvedCode:
,Code:
{row[2]:,d}Code:
e_bodyFor 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

