Throughout the first topics of this class we have used strings to represent words or phrases that we wanted to print out. Our definition was simple: a string is simply some characters inside quotes. In this chapter we explore strings in much more detail.
Strings can be defined as sequential collections of characters. This means that the individual characters that make up a string are in a particular order from left to right.
A string that contains no characters, often referred to as the empty string, is still considered to be a string. It is simply a sequence of zero characters and is represented by ‘ ’ or “” (two single or two double quotes with nothing in between).
The indexing operator (Python uses square brackets to enclose the index) selects a single character from a string. The characters are accessed by their position or index value. For example, in the string shown below, the 14 characters are indexed left to right from postion 0 to position 13.
It is also the case that the positions are named from right to left using negative numbers where -1 is the rightmost index and so on. Note that the character at index 6 (or -8) is the blank character.
Index Operator
The expression school[2]
selects the character at index 2 from school
, and creates a new string containing just this one character. The variable m
refers to the result.
The letter at index zero of "Luther College"
is L
. So at position [2]
we have the letter t
.
If you want the zero-eth letter of a string, you just put 0, or any expression with the value 0, in the brackets. Give it a try.
The expression in brackets is called an index. An index specifies a member of an ordered collection. In this case, the collection is characters in the string. The index indicates which character you want. It can be any integer expression so long as it evaluates to a valid index value.
Note that indexing returns a string of length 1.
Since strings are just a sequence of characters, we can traverse that sequence with a for loop. Try the following code and see what happens.