\[ \begin{align}\begin{aligned}\newcommand\blank{~\underline{\hspace{1.2cm}}~}\\% Bold symbols (vectors) \newcommand\bs[1]{\mathbf{#1}}\\% 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{\%}} % % Angle \newcommand\radian{\unit{rad}} \newcommand\degree{\unit{{}^\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 % % 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} \]

Oct 24, 2024 | 474 words | 5 min read

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

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 title(), xlabel(), and 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 subplot() function.

  • The subplot() function takes three arguments: the number of rows, the number of columns, and the index of the subplot.

  • Example:

    plt.subplot(2, 1, 1) # Create the first subplot
    plt.plot(x, y1)
    
    plt.subplot(2, 1, 2) # Create the second subplot
    plt.plot(x, y2)
    
  • You can create multiple plots in the same figure by calling the subplot() function multiple times.

  • The tight_layout() function is used to adjust the spacing between the plots.