Strings as sequences
Strings are sequences
We’ve already seen another sequence type: strings. Strings are nothing more than immutable sequences of characters (more accurately sequences of Unicode code points). Since a string is a sequence, we can use index notation to read individual characters from a string. For example:
>>> word = "omphaloskepsis" # which means "navel gazing"
>>> word[0]
'o'
>>> word[-1]
's'
>>> word[2]
'p'
We can use in
to check whether a substring is within a string. A substring is one or more contiguous characters within a string.
>>> word = "omphaloskepsis"
>>> "k" in word
True
>>> "halo" in word
True
>>> "chicken" in word
False
We can use min()
and max()
with strings. When we do, Python will compare characters (Unicode code points) within the string. In the case of min()
, Python will return the character with the lowest-valued code point. In the case of max()
, Python will return the character with the highest-valued code point.
We can also use len()
with strings. This returns the length of the string.
>>> word = "omphaloskepsis"
>>> max(word)
's'
>>> min(word)
'a'
>>> len(word)
14
Recall that Unicode includes thousands of characters, so these work with more than just letters in the English alphabet.
Comprehension check
- What is returned by
max('headroom')
? - What is returned by
min('frequency')
? - What is returned by
len('toast')
?
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.