Dec 03, 2024 | 474 words | 5 min read
8.1.1. Materials#
STRINGS#
Here is the link to the Python Official Documentation on strings
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 integerMembership 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#
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 filereadline()
method - reads a single line from the filereadlines()
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
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
andy
values of the data points you want to plot and then calling theplot()
function.The
plot()
function takes thex
andy
values as arguments and creates a line plot.The
show()
function is used to display the plot.The
title()
,xlabel()
, andylabel()
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.