Fred Agbo
September 18, 2026
== for
floating numeric comparisons! Rounding might result in unexpected
falsehoods
0.1 + 0.1 + 0.1 != 0.3STRING as an a data
type'I am a string'"I am also a string!""I'm sad you've gone"[
]
>>> A = [2, 4, 6, 8]
>>> print(A[1])
4
>>> B = "Spaghetti"
>>> print(B[6])
't'
+ operator concatenates sequences
+ will add two integers,
but will concatenate two strings>>> 'fish' + 'sticks'
'fishsticks'
>>> A = [1, 'fish']
>>> B = [2, 'fish']
>>> print(A + B)
[1, 'fish', 2, 'fish']
The number of elements in a sequence is commonly called its
length, and can be given by the
len( ) function
Simply place the sequence you desire to know the length of between the parentheses:
>>> len("spaghetti")
9You can have sequences of 0 length as well!
>>> A = ""
>>> B = [ ]
>>> print( len(A) + len(B) )
0chr and
ordchr takes a base-10 integer and returns
the corresponding Unicode character as a string
chr(65) gives
"A" (capital A)chr(960) gives
"π" (Greek letter pi)ord goes the other direction, taking a
single character string and returning the corresponding base-10 integer
of that character in Unicode
ord("B") gives 66ord(" ") gives 32ord("π") gives 960chr to get the
charactersrow=''
for i in range(32,127):
if len(row) == 16:
print(row)
row = ""
row = row + chr(i)
print(row)
You can select individual characters from the string using the syntax
string[k]
where string is the variable assigned to
the desired string and k is the index
integer of the character you want
>>> print("spaghetti sauce"[5])
eA common use case is to grab the last character of the string, using
s[-1]
which is shorthand for
s[len(s)-1]Often, you may want more than a single character
Python allows you to specify a starting and an ending index through an operation known as slicing
The syntax looks like:
string_variable[start : limit]
where start is the first index to be
included and everything up to but not including the
limit is included
start and
limit are actually optional (but the
: is not)
start omitted, the slice will begin
at the start of the stringlimit omitted, the slice will proceed
to the end of the stringCan add a third component to the slice syntax, called a stride
string_variable[start : limit : stride]Specifies how large the steps are between each included index
Can also make the stride negative to proceed backwards through a string
>>> s = "spaghetti sauce"
>>> s[4:8]
hett
>>> s[10:]
sauce
>>> s[:10:2]
sahti+) in Python to concatenate strings\[5+5+5+5+5+5 = 6 \times 5\]
print("Betelguese, " * 3)Python lets you use normal comparison operators to compare strings
string1 == string2
is true if string1 and
string2 contain the same characters in the
same order
Comparisons involving greater than or less than are done similar to alphabetical ordering
All comparisons are done according to their Unicode values.
"cat" > "CAT"Strings are what we call immutable: they can not be modified in place by clients.
You can “look” at different parts of the string, but you can not “change” those parts without making a whole new string
s = "Cats!"
s[0] = "R" # THIS WILL ERROR!!You can of course create a new string object with the desired traits:
s = "R" + s[1:]This applies to all methods that act on strings as well: they return a new string, they do not modify the original
| Method | Description |
|---|---|
string.find(pattern) |
Returns the first index of pattern in
string, or -1 if
it does not appear |
string.find(pattern, k) |
Same as the one-argument version, but starts searching at index
k |
string.rfind(pattern) |
Returns the last index of pattern is
string, or -1 if
missing |
string.rfind(pattern, k) |
Same as the one-argument version, but searches backwards from index
k |
string.startswith(prefix) |
Returns True if the string starts with
prefix |
string.endswith(suffix) |
Returns True if the string ends with
suffix |
| Method | Description |
|---|---|
string.lower() |
Returns a copy of string with all
letters converted to lowercase |
string.upper() |
Returns a copy of string with all
letters converted to uppercase |
string.capitalize() |
Returns a copy of string with the first
character capitalized and the rest lowercase |
string.strip() |
Returns a copy of string with whitespace
and non-printing characters removed from both ends |
string.replace(old, new) |
Returns a copy of string with all
instances of old replaced by
new |
| Method | Description |
|---|---|
char.isalpha() |
Returns True if
char is a letter |
char.isdigit() |
Returns True if
char is a digit |
char.isalnum() |
Returns True if
char is letter or a digit |
char.islower() |
Returns True if
char is a lowercase letter |
char.isupper() |
Returns True if
char is an uppercase letter |
char.isspace() |
Returns True if
char is a whitespace character (space, tab,
or newline) |
char.isidentifier() |
Returns True if
char is a legal Python identifier |
fleet ⟶ eetflay
orange ⟶
orangeway
from english import ENGLISH_WORDS, is_english_word
def find_first_vowel(word):
"""
Finds the first vowel index in a string
Algorithm:
Loop through all letters
Check if that letter is in aeiou
If it is, immediately return the index
"""
for i in range(len(word)):
if word[i].lower() in "aeiou":
return i
return -1
def pig_latin(word):
"""
Converts a word to its Pig Latin form
Algorithm:
Check the first letter to see if vowel
Task 1 if is not vowel
Figure out where first vowel is
Slice and rearrange
Task 2
Concatenate on a way
"""
first_vowel = find_first_vowel(word)
if first_vowel == 0:
# Easy tack on way
word += "way"
elif first_vowel > 0:
# Find first vowel and rearrange
first_part = word[:first_vowel]
second_part = word[first_vowel:]
word = second_part + first_part + "ay"
return word
if __name__ == '__main__':
for word in ENGLISH_WORDS:
platin = pig_latin(word)
if is_english_word(platin) and word != platin:
print(word, platin)
english.pyenglish library provides two objects
you can import into your programs:
ENGLISH_WORDS, which is a
list of all the valid words in the English dictionaryis_english_word(), which
accepts a single string as an argument and returns
True if the string represents a valid
English word.from english import ENGLISH_WORDS
count = 0
for word in ENGLISH_WORDS:
if len(word) == 2:
count += 1
print(count)
from english import is_english_word
count = 0
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for letter1 in alphabet:
for letter2 in alphabet:
word = letter1 + letter2
if is_english_word(word):
count += 1
print(count)