☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 4 : Output : Advanced Printing

Advanced Printing

Subscribe Contact


Overview

The print() function is the first function we learned. It's simple, effective, and very widely used in Python programming. But as your programming skills grow, you'll find that the basic print() function sometimes doesn't quite meet your needs. In this section, we'll explore advanced techniques for formatting and controlling console output that go beyond the basic print() function.


Using the String .format() Method

The string .format() method inserts specified value(s) into a string using placeholders. Placeholders are defined inside of the target string using curly brackets { }. The result of the format() method is a fully formatted string. These formatted strings can be used in print statements, assigned to variables, passed as parameters, etc. You can find official documentation for this method on the docs.python.org site.

Examples general form of the string format() method:

# Example 1:
string_var.format(Value_1, Value_2, ... Value_n)

# Example 2:
string_var.format("String {PlaceHolder_1} string {PlaceHolder_2} ... string {PlaceHolder_n}").format(Value_1, Value_2, ... Value_n)

One or more Values is required in the values list inside the format() method. Each value in the list must be separated by a comma and the values can be of any data type.

Code Examples

Study and practice the following code examples. Pay particular attention to the explanatory comments in the code as well. Also, you can find additional (more in-depth) documentation on string formatting here , and here , and here .

Also, you can find a list of the formatting type operators in the Reference Materials of this book on the String Formatting Types  page.

# Examples of the format() method

# Example of using a print statement with both the string and the variables
print("Hello, {}. Welcome to {}.".format("Bob", "the University of Utah"))
# Example of using a variable to hold the string
greeting = "Hello, {}. Welcome to {}."
print(greeting.format("Bob", "the University of Utah"))
print()

# Example using positional arguments
# Note the print statements are the same, but we can control the 
# order of printing based on where we put the placeholders {}
info = "Name: {0}, Age: {1}, University: {2}"
print(info.format("Bob", 22, "Utah"))
info = "University: {2}, Name: {0}, Age: {1}"
print(info.format("Bob", 22, "Utah"))
print()

# Example of using named arguments
# Note the print statements are the same, but we can control the 
# order of printing based on where we put the placeholders {}
template = "Artist: {name}, Album: {album}, Year: {year}"
print(template.format(name="Led Zepplin", album="Houses of the Holy", year=1973))
template = "Year: {year}, Album: {album}, Artist: {name}"
print(template.format(name="Led Zepplin", album="Houses of the Holy", year=1973))
print()

# Example of formatting numbers
# Formatting floating point numbers
print("Pi is approximately {0:.3f}.".format(3.14159))
# Formatting integers
print("Population: {0:,}".format(123456789))
# Formatting monetary values
print("Price: ${0:,.2f}".format(12345.67))
print()

# Example of padding and alignment formatting
# Right align
print("Username: {0:>5}".format("Bob"))
print("Username: {0:>10}".format("Bob"))
print("Username: {0:>20}".format("Bob"))
print("Username: {0:>20} Age: {1:>5}".format("Bob", 22))
print()
print("Username: {0:>10}\nAge: {1:>15}".format("Bob", 22))
print()

Output

Hello, Bob. Welcome to the University of Utah.
Hello, Bob. Welcome to the University of Utah.

Name: Bob, Age: 22, University: Utah
University: Utah, Name: Bob, Age: 22

Artist: Led Zepplin, Album: Houses of the Holy, Year: 1973
Year: 1973, Album: Houses of the Holy, Artist: Led Zepplin

Pi is approximately 3.142.
Population: 123,456,789
Price: $12,345.67

Username:   Bob
Username:        Bob
Username:                  Bob
Username:                  Bob Age:    22

Username:        Bob
Age:              22


Using f-strings

Python includes a concept called Formatted String Literals (f-strings). f-strings allow for inline expressions (called interpolation) within string literals. This feature makes formatting of console output more intuitive and readable. You can find full documentation for f-strings on the docs.python.org  site.

Code Examples

Study and practice the following code examples. Pay particular attention to the explanatory comments in the code as well.

# Examples of using f-strings

# Simple embedding example
name = "Bob"
print(f"Hello, {name}!")
print()

# Example of embedding expressions
x = 4
y = 5
print(f"The sum of {x} and {y} is {x + y}.")
print()

# Example of embedding formatted values
pi = 3.14159265
print(f"Pi rounded to three decimal places: {pi:.3f}")
print()

# Example of padding & alignment with f-strings
name = "Alice"
print(f"{name:>5}")
print(f"{name:>10}")
print(f"{name:>20}")
print()

# Example of multi-line f-strings
name = "Bob"
occupation = "Software Engineer"
print(f"""
Name:\t {name}
Job:\t {occupation}
""")
print()

Output

Hello, Bob!

The sum of 4 and 5 is 9.

Pi rounded to three decimal places: 3.142

Alice
     Alice
               Alice


Name:  Bob
Job:   Software Engineer


Using the String Template() Class

The string Template() class in Python's standard library provides a simple and more secure way to handle string substitution. It’s part of the string module and offers a straightforward syntax for string interpolation, using $ as a prefix for identifiers. This method is particularly useful when you need to generate text with variable parts, coming from user input or external sources, due to its simplicity and reduced risk of injection attacks.

Because the Template() class is in the standard library, we must import it in order to use it in our programs, like this:

from string import Template

Code Examples

Study and practice the following code examples. Pay particular attention to the explanatory comments in the code as well.

# Examples of the string Template() class

# First need to import the Template class 
from string import Template

# Simple substitution
# This example first creates a template and 
# then uses the substitute() method to 
# perform the substitution of the data value
# into the template 
t = Template("Go, $team!")
print(t.substitute(team="Utes"))
print()
print()

# Complex substitution
# In this example, we create an email template (form
# letter) with variables throughout that will be filled
# in by the substitute() method to produce a personalized
# email message.
email_template = Template("""
Dear $name,

Thank you for purchasing the $color $product. We hope you enjoy it!

Best regards,

Customer Service
""")
email = email_template.substitute(name='Bob', product='Widget 5000', color="red")
print(email)

Output

Go, Utes!



Dear Bob,

Thank you for purchasing the red Widget 5000. We hope you enjoy it!

Best regards,

Customer Service


Formatted Date & Time Printing

Printing dates and times in Python is a common task in many programming projects, ranging from logging activities in applications to processing and displaying temporal data in data science projects. Python provides a comprehensive standard library for handling dates and times through modules like datetime, time, and calendar. In this section, we'll focus on the datetime library, which is widely used for manipulating dates and times.



You can find a list of the date & time format code referred to below in the Reference Materials of this book on the Date & Time Format Codes  page.

Because datetime is a library we must import it in order to use it in our programs. In the case of the datetime library, it contains numerous useful modules so we'll use the from syntax to import several at once, like this:

from datetime import datetime, date, time

This line will import the datetime, date, and time modules.

Code Examples

Study and practice the following code examples. Pay particular attention to the explanatory comments in the code as well.

# Examples of formatting dates and times

# First need to import libraries
from datetime import datetime, date, time
import calendar

# The first example we'll consider is how to get the
# current date and time. To do this we'll use the
# now() function of the datetime module.
current_datetime = datetime.now()
print(current_datetime)
# Also, let's check the data type of the output of
# the now() function ...
print(type(current_datetime))
# ... Note that this is not a string, but rather it 
# is a datetime object so we will use numerous
# features of datetime to manipulate these objects
print()

# For example ...
print("Current Day:", current_datetime.day)
print("Current Month:", current_datetime.month)
print("Current Year:", current_datetime.year)
# ... we can use the day, month, and year attributes
# to get any of those components of the date stored
# in our variable.
print()

# The values for the day, month and year are useful,
# but we often want them formatted even more clearly
# for human readers. There are a few ways in which 
# we can format the output of dates and time. A very
# common approach is to use format codes (see the 
# Reference Materials Date & Time Format Codes page
# for a list the codes).

# Also, the strftime() method seen in the following examples
# is used to convert datetime object values into strings
# making it easy to concatenate those objects into output.

# As a reminder, here's the datetime in its original form...
print(current_datetime)
# ... and here are some examples of using the formatting codes
# to produce well-formatted date/time output ...
print("Year (4 digits):", current_datetime.strftime("%Y"))
print("Year (2 digits):", current_datetime.strftime("%y"))
print("Month (number with zero padding):", current_datetime.strftime("%m"))
print("Month (name, abbreviated):", current_datetime.strftime("%b"))
print("Month (full name):", current_datetime.strftime("%B"))
print("Day of the month (with zero padding):", current_datetime.strftime("%d"))
print("Day of the week (name, abbreviated):", current_datetime.strftime("%a"))
print("Day of the week (full name):", current_datetime.strftime("%A"))
print("Hour (24-hour clock, with zero padding):", current_datetime.strftime("%H"))
print("Hour (12-hour clock, with zero padding):", current_datetime.strftime("%I"))
print("Minute (with zero padding):", current_datetime.strftime("%M"))
print("Second (with zero padding):", current_datetime.strftime("%S"))
print("AM or PM:", current_datetime.strftime("%p"))
print("Locale's appropriate date and time:", current_datetime.strftime("%c"))
print("Full Date:", current_datetime.strftime("%A") + ", " + 
      current_datetime.strftime("%B") + " " + 
      current_datetime.strftime("%d") + ", " + current_datetime.strftime("%Y"))
print("Full Date and Time:", current_datetime.strftime("%m-%d-%Y %H:%M:%S"))

Output

2024-03-11 00:20:01.591502


Current Day: 11
Current Month: 3
Current Year: 2024

2024-03-11 00:20:01.591502
Year (4 digits): 2024
Year (2 digits): 24
Month (number with zero padding): 03
Month (name, abbreviated): Mar
Month (full name): March
Day of the month (with zero padding): 11
Day of the week (name, abbreviated): Mon
Day of the week (full name): Monday
Hour (24-hour clock, with zero padding): 00
Hour (12-hour clock, with zero padding): 12
Minute (with zero padding): 20
Second (with zero padding): 01
AM or PM: AM
Locale's appropriate date and time: Mon Mar 11 00:20:01 2024
Full Date: Monday, March 11, 2024
Full Date and Time: 03-11-2024 00:24:35








© 2023 John Gordon
Cascade Street Publishing, LLC