4.3. String Comparisons#
When strings are compared, they are compared lexicographic, meaning strings are put into alphabetical order and uppercase comes before lowercase and numbers come before the alphabets.
ASCII Table: https://www.rapidtables.com/code/text/ascii-table.html
Warning
Memorize the following:
0-9 – 48-57
A-Z – 65-90
a-z – 97-122
'A' < 'a'
True
'A' > 'Z'
False
'abc' < 'abd'
True
'abc' < 'abcd' # shorter is less
True
'1' < '2'
True
'1' < '20'
True
Warning
Numbers in strings are not naturally sorted!
'2' < '11'
is False
Convert a single character to its unicode number:
ord()
print(ord('0'))
print(ord('9'))
print(ord('A'))
print(ord('Z'))
print(ord('a'))
print(ord('b'))
48
57
65
90
97
98
Convert a unicode number to its unicode character:
chr()
print(chr(48))
print(chr(57))
print(chr(65))
print(chr(90))
print(chr(97))
print(chr(122))
0
9
A
Z
a
z
4.3.1. in
Operator#
Python provides a way to check if one string appears inside another one using the
in
operator.
'Jan' in '01 Jan 1838'
True
'Feb' in '01 Jan 1838'
False
'a' in 'abc'
True
'A' in 'abc'
False
4.3.2. Sorting by Hand#
Sort the following strings by hand:
['AABC', 'ABC', 'ABCD', '1', '2', '11', 'a', 'abc', 'b', 'abcd']
Show code cell source
result = ['1', '11', '2', 'AABC', 'ABC', 'ABCD', 'a', 'abc', 'abcd', 'b']
Sort the following strings by hand:
['Male21', 'Female25', 'Male30', 'Male2', 'Female24', 'Male11']
Show code cell source
result = ['Female24', 'Female25', 'Male11', 'Male2', 'Male21', 'Male30']