\[ \begin{align}\begin{aligned}\newcommand\blank{~\underline{\hspace{1.2cm}}~}\\% Bold symbols (vectors) \newcommand\bs[1]{\mathbf{#1}}\\% Differential \newcommand\dd[2][]{\mathrm{d}^{#1}{#2}} % use as \dd, \dd{x}, or \dd[2]{x}\\% Poor man's siunitx \newcommand\unit[1]{\mathrm{#1}} \newcommand\num[1]{#1} \newcommand\qty[2]{#1~\unit{#2}}\\\newcommand\per{/} \newcommand\squared{{}^2} \newcommand\cubed{{}^3} % % Scale \newcommand\milli{\unit{m}} \newcommand\centi{\unit{c}} \newcommand\kilo{\unit{k}} \newcommand\mega{\unit{M}} % % Percent \newcommand\percent{\unit{{\kern-4mu}\%}} % % Angle \newcommand\radian{\unit{rad}} \newcommand\degree{\unit{{\kern-4mu}^\circ}} % % Time \newcommand\second{\unit{s}} \newcommand\s{\second} \newcommand\minute{\unit{min}} \newcommand\hour{\unit{h}} % % Distance \newcommand\meter{\unit{m}} \newcommand\m{\meter} \newcommand\inch{\unit{in}} \newcommand\foot{\unit{ft}} % % Force \newcommand\newton{\unit{N}} \newcommand\kip{\unit{kip}} % kilopound in "freedom" units - edit made by Sri % % Mass \newcommand\gram{\unit{g}} \newcommand\g{\gram} \newcommand\kilogram{\unit{kg}} \newcommand\kg{\kilogram} \newcommand\grain{\unit{grain}} \newcommand\ounce{\unit{oz}} % % Temperature \newcommand\kelvin{\unit{K}} \newcommand\K{\kelvin} \newcommand\celsius{\unit{{}^\circ C}} \newcommand\C{\celsius} \newcommand\fahrenheit{\unit{{}^\circ F}} \newcommand\F{\fahrenheit} % % Area \newcommand\sqft{\unit{sq\,\foot}} % square foot % % Volume \newcommand\liter{\unit{L}} \newcommand\gallon{\unit{gal}} % % Frequency \newcommand\hertz{\unit{Hz}} \newcommand\rpm{\unit{rpm}} % % Voltage \newcommand\volt{\unit{V}} \newcommand\V{\volt} \newcommand\millivolt{\milli\volt} \newcommand\mV{\milli\volt} \newcommand\kilovolt{\kilo\volt} \newcommand\kV{\kilo\volt} % % Current \newcommand\ampere{\unit{A}} \newcommand\A{\ampere} \newcommand\milliampereA{\milli\ampere} \newcommand\mA{\milli\ampere} \newcommand\kiloampereA{\kilo\ampere} \newcommand\kA{\kilo\ampere} % % Resistance \newcommand\ohm{\Omega} \newcommand\milliohm{\milli\ohm} \newcommand\kiloohm{\kilo\ohm} % correct SI spelling \newcommand\kilohm{\kilo\ohm} % "American" spelling used in siunitx \newcommand\megaohm{\mega\ohm} % correct SI spelling \newcommand\megohm{\mega\ohm} % "American" spelling used in siunitx % % Capacitance \newcommand\farad{\unit{F}} \newcommand\F{\farad} \newcommand\microfarad{\micro\farad} \newcommand\muF{\micro\farad} % % Inductance \newcommand\henry{\unit{H}} \newcommand\H{\henry} \newcommand\millihenry{\milli\henry} \newcommand\mH{\milli\henry} % % Power \newcommand\watt{\unit{W}} \newcommand\W{\watt} \newcommand\milliwatt{\milli\watt} \newcommand\mW{\milli\watt} \newcommand\kilowatt{\kilo\watt} \newcommand\kW{\kilo\watt} % % Energy \newcommand\joule{\unit{J}} \newcommand\J{\joule} % % Composite units % % Torque \newcommand\ozin{\unit{\ounce}\,\unit{in}} \newcommand\newtonmeter{\unit{\newton\,\meter}} % % Pressure \newcommand\psf{\unit{psf}} % pounds per square foot \newcommand\pcf{\unit{pcf}} % pounds per cubic foot \newcommand\pascal{\unit{Pa}} \newcommand\Pa{\pascal} \newcommand\ksi{\unit{ksi}} % kilopound per square inch \newcommand\bar{\unit{bar}} \end{aligned}\end{align} \]

Dec 04, 2025 | 927 words | 9 min read

10.1.1. Materials#

Strings#

Here is the link to the Python Official Documentation on strings

01_strings.py

Strings as sequences of characters#

A string is a sequence of characters. In Python, strings are immutable sequences of Unicode code points.

String literals#

A string literal is a sequence of characters enclosed in single quotes (’…’) or double quotes (”…”).

String manipulation as an immutable sequence#

For strings x and y with indices i, j and k, the following operations are supported:

  • Indexing : x[i], x[-i]

  • Slicing : x[i:j], x[i:j:k] # start, stop, step

  • Concatenation : x + y

  • Repetition : n * x, where n is an integer

  • Membership test : x in y, x not in y

  • Length : len(x), min(x), max(x)

  • Iteration : for i in x

  • Comparison : x == y, x != y, x < y, x <= y, x > y, x >= y

  • Searching : x.find(y), x.rfind(y), x.index(y), x.rindex(y)

  • Counting : x.count(y)

  • Ordering : sorted(x), reversed(x)

String methods#

For strings x and y, the following methods are supported:

- x.lower()      # lowers the case of all characters
- x.upper()      # uppercases all characters
- x.title()      # capitalizes the first character of each word
- x.capitalize() # capitalizes the first character of the string
- x.split()      # splits a string into a list of substrings
- x.strip()      # removes leading and trailing whitespace (lstrip, rstrip)
- x.replace()    # replaces a substring with another substring (old, new)
- x.join()       # joins a list of substrings into a single string
- x.startswith() # checks if a string starts with a specified prefix (prefix, start, end)
- x.endswith()   # checks if a string ends with a specified suffix
- x.isalpha()    # checks if all characters are alphabetic, returns Boolean
- x.isdigit()    # checks if all characters are digits, returns Boolean
- x.isalnum()    # checks if all characters are alphanumeric, returns Boolean
- x.islower()    # checks if all characters are lowercase, returns Boolean
- x.isupper()    # checks if all characters are uppercase, returns Boolean
- x.isspace()    # checks if all characters are whitespace, returns Boolean

File I/O#

02_file_io.py hail_purdue.txt

The playing_with_strings.py file is a Python script which shows you how to use the strip() and split() functions. Open this file in VS Code, read it, and experiment with it before doing the next exercise.

File Input#

open() function#

Opens a file and returns a file object.

Syntax: open(file, mode)

Example: f = open("hail_purdue.txt", "r")

  • read mode (default) - “r”

  • write mode - “w”

  • append mode - “a”

  • binary mode - “b”

  • read/write mode - “r+”

  • read/write binary mode - “rb+”

  • read/write append mode - “a+”

  • read/write append binary mode - “ab+”

close() function#

Closes the file. Must be called after the file is opened.

Syntax: f.close()

with statement#

automatically closes the file

Syntax:

with open(file, mode) as f:
   # code block
  • read() method - reads the entire file

  • readline() method - reads a single line from the file

  • readlines() method - reads all the lines from the file

File Output#

write() method - writes a string to the file

writelines() method - writes a list of strings to the file

pathlib#

The pathlib package provides a convenient way to handle file paths and directories using methods and attributes tailored for path manipulations.

Here is the link to the Python Official Documentation on pathlib

pathlib is a built-in Python library that provides an object-oriented approach to working with filesystem paths. It allows you to easily manipulate, traverse, and interact with directories (a.k.a. folders) and files.

Commonly Used pathlib Methods#

Table 10.1 Commonly Used Methods#

Method

Description

.iterdir()

Can iterate over files and directories in the given path. This makes it easy to check file extensions and process each file individually.

.name

Can be used to access the filename.

.suffix

Can be used to access the extension from a path.

Using pathlib#

Since pathlib is included in Python 3.4 and later, so no pip installation is required. You can simply import it as follows:

from pathlib import Path

Exploring Directories:#

  • You can check whether a directory exists and whether it is a folder:

    from pathlib import Path
    
    directory = Path("dataset")  # Replace with your actual directory path
    
    if directory.exists() and directory.is_dir():
       print(f"{directory} exists and is a folder.")
    else:
       print(f"{directory} does not exist.")
    
  • You can list all files and subdirectories in a given directory:

    for item in directory.iterdir():
       print(item)  # Prints each file or folder within the directory
    

Viewing Files and their Extensions:#

  • You can filter files by their extensions (such as .png or .jpg):

    # Find all CSV files in the directory
    csv_files = list(directory.glob("*.csv"))
    print("CSV Files:", csv_files)
    
    # Find all PNG and JPG image files in the directory
    image_files = list(directory.glob("*.png")) + list(directory.glob("*.jpg"))
    print("Image Files:", image_files)
    

matplotlib#

Here is the link to the Python Official Documentation on matplotlib

03_matplotlib.py

matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy.

Installing matplotlib#

Enter the following command in the terminal:

python3 -m pip install matplotlib

Basic Plotting:#

  • The most basic plot is the line plot.

  • A line plot is created by specifying the x and y values of the data points you want to plot and then calling the plot() function.

  • The plot() function takes the x and y values as arguments and creates a line plot.

  • The show() function is used to display the plot.

  • The set_title(), set_xlabel(), and set_ylabel() functions are used to set the title, x-axis label, and y-axis label of the plot, respectively.

  • The savefig() function is used to save the plot as an image file.

Types of Plots#

  • matplotlib provides a variety of plots that can be used to visualize data.

  • Some commonly used plots are: Line Plot, Scatter Plot, Bar Plot, Histogram, Pie Chart, Box Plot, Heatmap, etc.

Customizing Plots#

  • matplotlib allows you to customize the appearance of the plots by setting various properties such as the color, line style, marker style, etc.

  • You can also add labels, titles, legends, and annotations to the plots.

Multiple Plots#

  • You can create multiple plots in the same figure by using the subplots() function.

  • The first two arguments to the subplots() function are the number of rows and the number of columns

  • Example:

    fig, ax = plt.subplots(2, 1)
    
    ax[0].plot(x, y1)
    
    ax[1].plot(x, y2)
    
  • The tight_layout() function is used to adjust the spacing between the plots.

Pillow (PIL)#

Here is the link to the Official Documentation on PIL

PIL stands for the Python Imaging Library and adds image processing capabilities to python.

Installing PIL#

Enter the following command in the terminal:

python3 -m pip install Pillow

Important submodules#

We will primarily be using these submodules for this class:

from PIL import Image
from PIL import ImageOps

Read more about the functionalities of these submodules in the Image documentation and ImageOps documentation.

Opening an Image File:#

  • You can open an image file using the Image.open() function. Note that this does not return a NumPy array, but a PIL image object. However, you can convert it to a NumPy array.

Creating an Image from an array:#

  • You can use the Image.fromarray() function to create an image from a NumPy array.

Determining Image Attributes:#

  • The Image type contains several useful attributes such as the mode (RGB, RGBA, L, etc.), size (width, height), and format (JPEG, PNG, etc.) of the image. Explore the documentation to find these attributes.

Resizing Images:#

  • You can resize an image using the resize() method of the Image object.

  • This method has a parameter called resample which dictates how new pixels in the resamples image are created or what happens to the old pixels in the original image. Some options are:

    • Image.Resampling.NEAREST - Nearest Neighbor (default)

    • Image.Resampling.BILINEAR - Bilinear

    • Image.Resampling.HAMMING - Hamming

    • Image.Resampling.BICUBIC - Bicubic

    • Image.Resampling.LANCZOS - Lanczos

  • Read about the different resampling filter methods in the documentation.

Padding Images:#

  • You can pad an image using the ImageOps.pad() function.

  • You must select the desired color of the padded area and what the shape of the final padded image should be.

OpenCV#

Here is the link to the Official Python Documentation on OpenCV

OpenCV stands for Open Source Computer Vision Library. Unlike PIL, which is primarily used for basic image processing tasks, OpenCV is a powerful library designed for real-time computer vision and image analysis. Hence, it has several advanced image processing functionalities.

Installing OpenCV#

Enter the following command in the terminal:

python3 -m pip install opencv-python

Importing OpenCV#

  • Even though the package name is opencv-python, it is imported as cv2.

import cv2