The most important concept of this chapter is that of a string as a sequence of characters. If you learn nothing else, be sure to understand that:
Since a string is a sequence, we can loop through its values, which are the individual characters of the sequence:
for c in s:
do something with c, the current characterWe can ask the length of a string:
len(s)
Knowing the length, we can also loop using an index:
for i in range(len(s)):
do something with s[i], the current characterWe can index a string; index values start at 0:
s[i]We can slice a string, obtaining a substring:
s[i:j]
The index values i and j are the start and end of the substring; as in a range expression, the start is included, the end is not.
We can concatenate two strings, using the + operator; and we can repeat a string, using the * operator.
Also understand that characters are represented by numeric codes; they can be converted to and from these codes:
ord(c)
chr(i)
Our main objective is to learn about strings—sequences of characters. I'm going to try to de-emphasize codes (as in secret codes, cryptography). Codes are here as an example of an application of string processing. In the past, students have gotten bewildered about codes and failed to grasp strings thoroughly. Still, I hope we do pick up some concepts about codes as well.
Also, I'm introducing here some learning objectives about code style and management of complexity.