Pythonlearn. Chapter 6. Extract (79-90)
Pythonlearn. Chapter 6. Extract (79-90)
Strings
The second statement extracts the character at index position 1 from the fruit
variable and assigns it to the letter variable.
The expression in brackets is called an index. The index indicates which character
in the sequence you want (hence the name).
But you might not get what you expect:
>>> print(letter)
a
For most people, the first letter of “banana” is “b”, not “a”. But in Python, the
index is an offset from the beginning of the string, and the offset of the first letter
is zero.
So “b” is the 0th letter (“zero-th”) of “banana”, “a” is the 1th letter (“one-th”),
and “n” is the 2th (“two-th”) letter.
You can use any expression, including variables and operators, as an index, but
the value of the index has to be an integer. Otherwise you get:
67
68 CHAPTER 6. STRINGS
b a n a n a
[0] [1] [2] [3] [4] [5]
To get the last letter of a string, you might be tempted to try something like this:
The reason for the IndexError is that there is no letter in “banana” with the index
6. Since we started counting at zero, the six letters are numbered 0 to 5. To get
the last character, you have to subtract 1 from length:
Alternatively, you can use negative indices, which count backward from the end of
the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the
second to last, and so on.
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
6.4. STRING SLICES 69
This loop traverses the string and displays each letter on a line by itself. The
loop condition is index < len(fruit), so when index is equal to the length of
the string, the condition is false, and the body of the loop is not executed. The
last character accessed is the one with the index len(fruit)-1, which is the last
character in the string.
Exercise 1: Write a while loop that starts at the last character in the string and
works its way backwards to the first character in the string, printing each letter on
a separate line, except backwards.
Another way to write a traversal is with a for loop:
Each time through the loop, the next character in the string is assigned to the
variable char. The loop continues until no characters are left.
The operator [n:m] returns the part of the string from the “n-th” character to the
“m-th” character, including the first but excluding the last.
If you omit the first index (before the colon), the slice starts at the beginning of
the string. If you omit the second index, the slice goes to the end of the string:
If the first index is greater than or equal to the second the result is an empty string,
represented by two quotation marks:
An empty string contains no characters and has length 0, but other than that, it
is the same as any other string.
Exercise 2: Given that fruit is a string, what does fruit[:] mean?
70 CHAPTER 6. STRINGS
It is tempting to use the operator on the left side of an assignment, with the
intention of changing a character in a string. For example:
The “object” in this case is the string and the “item” is the character you tried
to assign. For now, an object is the same thing as a value, but we will refine that
definition later. An item is one of the values in a sequence.
The reason for the error is that strings are immutable, which means you can’t
change an existing string. The best you can do is create a new string that is a
variation on the original:
This example concatenates a new first letter onto a slice of greeting. It has no
effect on the original string.
The following program counts the number of times the letter “a” appears in a
string:
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)
The word in is a boolean operator that takes two strings and returns True if the
first appears as a substring in the second:
The comparison operators work on strings. To see if two strings are equal:
if word == 'banana':
print('All right, bananas.')
Other comparison operations are useful for putting words in alphabetical order:
Python does not handle uppercase and lowercase letters the same way that people
do. All the uppercase letters come before all the lowercase letters, so:
Strings are an example of Python objects. An object contains both data (the actual
string itself) and methods, which are effectively functions that are built into the
object and are available to any instance of the object.
Python has a function called dir which lists the methods available for an object.
The type function shows the type of an object and the dir function shows the
available methods.
72 CHAPTER 6. STRINGS
capitalize(self, /)
Return a capitalized version of the string.
While the dir function lists the methods, and you can use help to get some simple
documentation on a method, a better source of documentation for string methods
would be
https://docs.python.org/library/stdtypes.html#string-methods.
Calling a method is similar to calling a function (it takes arguments and returns
a value) but the syntax is different. We call a method by appending the method
name to the variable name using the period as a delimiter.
For example, the method upper takes a string and returns a new string with all
uppercase letters:
Instead of the function syntax upper(word), it uses the method syntax
word.upper().
This form of dot notation specifies the name of the method, upper, and the name
of the string to apply the method to, word. The empty parentheses indicate that
this method takes no argument.
A method call is called an invocation; in this case, we would say that we are
invoking upper on the word.
For example, there is a string method named find that searches for the position
of one string within another:
6.9. STRING METHODS 73
In this example, we invoke find on word and pass the letter we are looking for as
a parameter.
The find method can find substrings as well as characters:
>>> word.find('na')
2
>>> word.find('na', 3)
4
One common task is to remove white space (spaces, tabs, or newlines) from the
beginning and end of a string using the strip method:
You will note that startswith requires case to match, so sometimes we take a line
and map it all to lowercase before we do any checking using the lower method.
In the last example, the method lower is called and then we use startswith to
see if the resulting lowercase string starts with the letter “h”. As long as we are
careful with the order, we can make multiple method calls in a single expression.
Exercise 4: There is a string method called count that is similar to the function
in the previous exercise. Read the documentation of this method at:
https://docs.python.org/library/stdtypes.html#string-methods
Write an invocation that counts the number of times the letter a occurs in “banana”.
74 CHAPTER 6. STRINGS
>>> camels = 42
>>> f'{camels}'
'42'
The result is the string ‘42’, which is not to be confused with the integer value 42.
An expression can appear anywhere in the string, so you can embed a value in a
sentence:
6.12. DEBUGGING 75
>>> camels = 42
>>> f'I have spotted {camels} camels.'
'I have spotted 42 camels.'
Several expressions can be included within a single string literal in order to create
more complex strings.
>>> years = 3
>>> count = .1
>>> species = 'camels'
>>> f'In {years} years I have spotted {count} {species}.'
'In 3 years I have spotted 0.1 camels.'
Formatted string literals are powerful, and they can do even more than is covered
here. You can read more about them at
https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals.
6.12 Debugging
A skill that you should cultivate as you program is always asking yourself, “What
could go wrong here?” or alternatively, “What crazy thing might our user do to
crash our (seemingly) perfect program?”
For example, look at the program which we used to demonstrate the while loop
in the chapter on iteration:
while True:
line = input('> ')
if line[0] == '#':
continue
if line == 'done':
break
print(line)
print('Done!')
# Code: https://www.py4e.com/code3/copytildone2.py
Look what happens when the user enters an empty line of input:
The code works fine until it is presented an empty line. Then there is no zero-th
character, so we get a traceback. There are two solutions to this to make line three
“safe” even if the line is empty.
One possibility is to simply use the startswith method which returns False if
the string is empty.
if line.startswith('#'):
Another way is to safely write the if statement using the guardian pattern and
make sure the second logical expression is evaluated only where there is at least
one character in the string:
6.13 Glossary
counter A variable used to count something, usually initialized to zero and then
incremented.
empty string A string with no characters and length 0, represented by two quo-
tation marks.
flag A boolean variable used to indicate whether a condition is true or false.
invocation A statement that calls a method.
immutable The property of a sequence whose items cannot be assigned.
index An integer value used to select an item in a sequence, such as a character
in a string.
item One of the values in a sequence.
method A function that is associated with an object and called using dot notation.
object Something a variable can refer to. For now, you can use “object” and
“value” interchangeably.
search A pattern of traversal that stops when it finds what it is looking for.
sequence An ordered set; that is, a set of values where each value is identified by
an integer index.
slice A part of a string specified by a range of indices.
traverse To iterate through the items in a sequence, performing a similar opera-
tion on each.
6.14 Exercises
Exercise 5: Slicing strings
Take the following Python code that stores a string:
str = 'X-DSPAM-Confidence: 0.8475'
Use find and string slicing to extract the portion of the string after the colon
character and then use the float function to convert the extracted string into a
floating point number.
6.14. EXERCISES 77