Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Print a String and an Integer
1
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

[Image: 1f4ac.png] 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
    Code:
    print()
    function

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

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

  • Method 4: Use the
    Code:
    %d
    ,
    Code:
    %s
    and
    Code:
    %f
    operators

  • Method 5: Use identification numbers

  • Method 6: Use
    Code:
    f-string
    conditionals

  • Bonus: Format CSV for output

Method 1: Use the print() function

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

Code:
print('Steve', 39915)

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

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

Steve 39915

[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]

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

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

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

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

Steve has solved 39915 puzzles!

[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]

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

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

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

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

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

Steve has solved 39915 puzzles!

[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]

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

Code:
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!

[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]

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

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

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 += 1

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

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

Inside the loop, the
Code:
%s
(accepts strings) is replaced with the value of
Code:
f_name[i]
. Then,
Code:
%d
(accepts integers) is replaced with the value of
Code:
f_solved[i]
. Finally, the %3.2f (for floats) value of is replaced with
Code:
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.

[Image: 1f4a1.png]Note: In the
Code:
%3.2f
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]

Method 5: Use identification numbers

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

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:
Lists
are declared. Each
Code:
List
carries different information for each Finxter user (
Code:
f_name
,
Code:
f_solved
).

Then, using a
Code:
For
loop, the code runs through the above
Code:
Lists
. The numbers wrapped inside curly braces (
Code:
{0}, {1}
) indicate holding places for the expected data. This data appears inside the
Code:
format()
function (
Code:
(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!

[Image: 1f4a1.png]Note: The data in
Code:
f_solved
is formatted to display a thousand comma (
Code:
',d'
).

Method 6: Use f-string and a conditional

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

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:
List
carries different information for each Finxter user (
Code:
f_name
,
Code:
f_solved
).

Inside the
Code:
print()
function, the code inside the curly braces (
Code:
{}
) 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.

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
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
Code:
finxters
.

[Image: 1f4a1.png]Note: The underscore (
Code:
_
) character in the
Code:
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 (
Code:
row[3])
. This email address saves to
Code:
user_email
.

Next, the custom email body is formatted using the
Code:
f-string
and passed the user’s First Name and Last Name in the salutation (
Code:
{row[0]} {row[1]}
). Then, the
Code:
solved
variable is formatted to display commas (
Code:
,
) indicating thousands (
Code:
{row[2]:,d}
). The results are saved to
Code:
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

[Image: 1f9e9.png]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

[Image: image-119.png]
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: