Strings in Python (Part II)
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
>>> s = 'Monty Python'
>>> print s[0:5]
>>> print s[6:13]
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:
>>> fruit = 'banana'
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
This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time an a is found. When the loop exits, count contains the result—the total number of a’s.
The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second:
>>> 'a' in 'banana'
>>> 'seed' in 'banana'
The format operator, % allows us to construct strings, replacing parts of the strings with the data stored in variables. When applied to integers, % is the modulus operator. But when the first operand is a string, % is the format operator. The first operand is the format string, which contains one or more format sequences that specify how the second operand is formatted. The result is a string. For example, the format sequence ‘%d’ means that the second operand should be formatted as an integer (d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
The result is the string ’42’, which is not to be confused with the integer value 42.
A format sequence can appear anywhere in the string, so you can embed a value in a sentence:
>>> camels = 42
>>> 'I have spotted %d camels.' % camels
‘I have spotted 42 camels.’