Lectures‎ > ‎

Week06

Strings

  • Compound types and the bracket operator []
    • s = "Hello World"
    • print s[6]
    • c = s[1]
  • Indexing
    • Indicies start at 0
    • print s[0]
    • Can index from end of string with negative numbers: print s[-1]
  • Length (len)
    • Returns length of string
    • len(s)
  • Loop traversal: while
    • We can use our loop template to traverse s string.
  • Loop traversal: for
    • It is easier to use a for loop:

      for c in s:
          print c

  • Slices
    • We can extract a substring from a string using a slice:
    • print s[0:5]
    • Does not include the last index.
    • print s[6:]
  • Comparison
    • Lexigraphical order
    • s2 = "Abracadabra"
    • s2 < s
  • Immutability
    • Can't alter strings: s[0] = "b'' won't work.
    • Instead, you just create a new string
    • s_new = "Bye " + s[6:]
    • print s_new
  • The in operator
    • You can determine if a character is in a string using "in"
    • "e" in s
  • Example: count characters
    • We want to write a function that determine how many times a character occurs in a string:
    • def occurrences(s, c):

Lists

  • Notation
  • Accessing
  • Iteration
ċ
form2.html
(0k)
Greg Benson,
Sep 25, 2012, 4:26 PM
ċ
list_helper.py
(0k)
Greg Benson,
Sep 25, 2012, 4:27 PM
ċ
result2.py
(1k)
Greg Benson,
Sep 25, 2012, 4:26 PM
Comments