### CS150 - Fall 2011 - Class 6

• Problem set 5 problem 1

- Section A: sorry for going over
- Do the Lab prep for Friday! It's particularly important for this lab.
- CS lunch talk tomorrow 12:20 in MBH 104: Identification of Individual Spotted Salamanders
- extra credit if you attend and submit a 1 paragraph summary

• A quick review of strings
- we can concatenate strings
>>> "this is " + "multiple " + "strings"
'this is multiple strings'
- if we want to merge a string and a number, we need to convert the number to a string
>>> year = 2011
>>> "The current year is " + str(year)
'The current year is 2011'
- we can index particular characters in the string using []'s. Indexing starts at 0
>>> test = "a string"
>>> test[0]
'a'
>>> test[2]
's'
>>> test[-2]
'n'
- we can get a substring (or part) of a string using slicing, giving a range of indices
>>> test[2:4]
'st'
>>> test[1:6]
' stri'
- We commonly want to iterate over the characters in a string. We can do this using range over the length of the string

for i in range(len(test)):
print test[i] # do something with test[i]

- Strings are also objects
- objects represent data
- but they also have "methods" that we can call on them
- to call a method, we use the '.' notation

>>> "this is a string".upper()
'THIS IS A STRING'
>>> "this is a string".capitalize()
'This is a string'
>>> "this is a string".find("a")
8

• What other methods might we want for strings?
- upper / lower
- find
- replace
- startswith
- isalnum
- isalpha
- isdigit
- islower
- isupper
- Many more, look at the documentation: http://docs.python.org/library/string.html

• A few examples to try
>>> test = " A string"
>>> test[4]
't'
>>> test[-5]
't'
>>> test[-10]
Traceback (most recent call last):
File "<string>", line 1, in <fragment>
IndexError: string index out of range
>>> test[0:2]
' A'
>>> test[2:7]
' a stri'
>>> test[7:]
'ng'
>>> test.lower()
" a string"
>>> test.upper()
" A STRING"
>>> test.find("i")
6
>>> test.find("ring")
5
>>> test.find("A string")
1
>>> test.find("banana");
-1
>>> " This is a string".find("i", 4)
6
>>> test.replace("s", "S")
" A String"
>>> test.replace("stri", "ris");
" A rising"
>>> "This is a string".replace("i", "")
"Ths s a strng"
>>> test.upper()[3:]
"STRING"
>>> test.upper().replace("i", "n").lower().find("n")
>>> test[0:3] + "longer " + test[3:]
" A longer string"
>>> test.startswith(" A ")
True
>>> test.startswith(" a")
False
>>> test.endswith("n");
False
>>> test.endswith("string");
True
>>> test.lower()[6:8].startswith("i")
True

• strings are immutable!
- test.replace("i", "a") does NOT change test
- test.upper() does NOT changes test to upper case, but returns a new string that is the capitalize version