stringsare qualitatively different because they are made up of smaller pieces -- characters.
stringsare an example of a compound data type.
The square brackets operator(
]), which selects and
reads a single character from a
>>> fruit = "banana" >>> letter = fruit >>> 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 >>> print letter b
lenfunction 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]
index = 0 while index < len(fruit): letter = fruit[index] print letter index = index + 1The name of the loop variable is
for char in fruit: print charThe following example uses concatenation and a for loop:
prefixes = "JKLMNOPQ" suffix = "ack" for letter in prefixes: print letter + suffixThe 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.
>>> x = 'banana' >>> x[:3] 'ban' >>> x[3:] 'ana'
s[:]returns the entire string:
>>> x = 'banana' >>> x[:] 'banana'
strings. 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 = '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.
def find(str, ch): index = 0 while index < len(str): if str[index] == ch: return index index = index + 1 return -1
findis the opposite of the
'a'appears in a string:
fruit = "banana" count = 0 index = 0 for char in fruit: if char == 'a': count = count + 1 print countThis program demonstrates another common idiom, called a counter.
countis initialized to zero and incremented each time we find an
countcontains the result: the total number of
>>> import stringThe module includes a function named
findthat 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.
findwe want using the dot operator.
string.findis more general than the version we wrote.
>>> string.find("banana", "na") 2
>>> string.find("banana", "na", 3) 4
>>> string.find("bob", "b", 1, 2) -1In this example, the search fails because the letter
"b"does not appear in the index range from
>>> print string.lowercase abcdefghijklmnopqrstuvwxyz >>> print string.uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ >>> print string.digits 0123456789We can use these constants and
findto classify characters:
def isLower(ch): return find(string.lowercase, ch) != -1This can also be implemented using the comparison operator:
def isLower(ch): return 'a' <= ch <= 'z'