ints, floats and strings.
strings are qualitatively different because they are made up of smaller
pieces -- characters. strings are an example of a compound data type.string.
The square brackets operator([ and ]), which selects and
reads a single character from a string:
>>> fruit = "banana" >>> letter = fruit[1] >>> print letterThe output is:
aNot the expected result
b. Strings in Python start with an index of 0,
so the zero-eth letter is
>>> letter = fruit[0] >>> print letter b
len function returns the number of characters in the given string:
>>> fruit = "banana" >>> len(fruit) 6The WRONG way to find the last letter of a string:
length = len(fruit) last = fruit[length] # ERROR!This is wrong because the letters are numbered from 0 to 5.
length = len(fruit) last = fruit[length-1]Python also supports negative indices, which count backwards from the end of the string:
last = fruit[-1] secondToLast = fruit[-2]
for loopwhile statement:
index = 0
while index < len(fruit):
letter = fruit[index]
print letter
index = index + 1
The name of the loop variable is index.
for loop.
for char in fruit:
print char
The following example uses concatenation and a for loop:
prefixes = "JKLMNOPQ"
suffix = "ack"
for letter in prefixes:
print letter + suffix
The output of this program is:
Jack Kack Lack Mack Nack Oack Pack QackFYI: this is an abecedarian series, where the elements appear in alphabetical order.
>>> s = "Peter, Paul, and Mary" >>> print s[0:5] Peter >>> print s[7:11] Paul >>> print s[17:21] MaryThe operator
[n:m] returns the part of the string from the
nth character to the mth character, including the
first, but excluding the last.
image from How to Think Like a Computer Scientist: Python Version
>>> x = 'banana' >>> x[:3] 'ban' >>> x[3:] 'ana'
s[:] returns the entire string:
>>> x = 'banana' >>> x[:] 'banana'
string comparisonstrings. To
see if two strings are equal:
if word == "banana":
print "Yes, we have no bananas!"
Other comparison operations are useful for putting words in alphabetical
order.
if word < "banana":
print "Your word," + word + ", comes before banana."
elif word > "banana":
print "Your word," + word + ", comes after banana."
else:
print "Yes, we have no bananas!"
Python does not handle upper and lower
case letters the same way that people do. All the upper case letters come before
all the lower case letters:
Your word, Zebra, comes before banana.A common way to address this problem is to convert strings to a standard format, like all lower-case, before performing the comparison.
strings are not mutable[] operator cannot be used on the left side of an assignment:
greeting = "Hello, world!" greeting[0] = 'J' # ERROR! print greetingInstead of producing the output
Jello, world!, this code
produces an error message like
TypeError: object doesn't support item assignmentAn alternative is to create a new string by concatenating a new character and the remainder of the original string:
greeting = "Hello, world!" new_greeting = 'J' + greeting[1:] print new_greetingKeep in mind that this operation does not modify the original string.
find function
def find(str, ch):
index = 0
while index < len(str):
if str[index] == ch:
return index
index = index + 1
return -1
find is the opposite of the [] operator.
-1.'a'
appears in a string:
fruit = "banana"
count = 0
index = 0
for char in fruit:
if char == 'a':
count = count + 1
print count
This program demonstrates another common idiom, called a counter.
count is initialized to zero and incremented each
time we find an 'a'.
count contains the result: the total
number of a's. string module>>> import stringThe module includes a function named
find that does the same
thing as the function we wrote. To call it,
>>> fruit = "banana" >>> index = string.find(fruit, "a") >>> print index 1We specify the name of the module and the name of the function.
find we want using the dot operator.string.find is more general than the version we wrote.
>>> string.find("banana", "na")
2
>>> string.find("banana", "na", 3)
4
>>> string.find("bob", "b", 1, 2)
-1
In this example, the search fails because the letter "b" does
not appear in the index range from 1 to 2 (not
including 2).
>>> print string.lowercase abcdefghijklmnopqrstuvwxyz >>> print string.uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ >>> print string.digits 0123456789We can use these constants and
find to classify characters:
def isLower(ch):
return find(string.lowercase, ch) != -1
This can also be implemented using the comparison operator:
def isLower(ch):
return 'a' <= ch <= 'z'