CMU 15-110: Principles of Computing
Strings: Part 1


  1. String Literals
  2. Some String Constants
  3. Some String Operators
  4. Looping over Strings
  5. Strings are Immutable
  6. Some String-related Functions
  7. Some String Methods
  8. Basic File IO

  1. String Literals
    1. Four kinds of quotes
      print('single-quotes') print("double-quotes") print('''triple single-quotes''') print("""triple double-quotes""")

  2. Some String Constants
    import string print(string.ascii_letters) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz print(string.ascii_uppercase) # ABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.digits) # 0123456789 print(string.punctuation) # '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' print(string.whitespace) # space + tab + linefeed + return + ...

  3. Some String Operators
    1. String + and *
      print('abc' + 'def') print('abc' * 3) print('abc' + 3) # error

    2. The in operator
      print('ring' in 'strings') print('wow' in 'amazing!') print('Yes' in 'yes!') print('' in 'No way!')

    3. String indexing and slicing
      1. Indexing a single character
        s = 'abcdefgh' print(s) print(s[0]) print(s[1]) print(s[len(s)-1]) print(s[len(s)]) # crashes (string index out of range)

      2. Negative indexes
        s = 'abcdefgh' print(s) print(s[-1]) print(s[-2]) print(s[-len(s)]) print(s[-len(s)-1]) # crashes (string index out of range)

      3. Slicing a range of characters
        s = 'abcdefgh' print(s) print(s[0:4]) print(s[2:4])

  4. Looping over Strings
    1. "for" loop with indexes
      s = 'abcd' for i in range(len(s)): print(i, s[i])

    2. "for" loop without indexes
      s = 'abcd' for c in s: print(c)

  5. Strings are Immutable
    1. You cannot change strings! They are immutable.
      s = 'abcde' s[2] = 'z' # Error! Cannot assign into s[i]

    2. Instead, you must create a new string
      s = 'abcde' s = s[:2] + 'z' + s[3:] print(s)

  6. Some String-related Functions
    1. input(), str(), and len()
      name = input('Enter your name: ') print('Hi, ' + name + '. Your name has ' + str(len(name)) + ' letters!')

    2. chr() and ord()
      print(ord('A')) # 65 print(chr(65)) # 'A' print(chr(ord('A')+1)) # ?

  7. Some String Methods
    1. String tests
      s.isalpha()True if s only contains letters A-Z,a-z
      s.isdigit()True if s only contains digits 0-9
      s.isspace()True if s only contains whitespace (spaces, tabs, newlines)
      s.islower()True if the letters in s are all lowercase (a-z)
      s.isupper()True if the letters in s are all uppercase (A-Z)

    2. String edits
      s.lower()Returns a copy of s in lowercase
      s.upper()Returns a copy of s in uppercase

      For example:
      print('This is nice. Yes!'.lower()) print('So is this? Sure!!'.upper())

  8. Basic File IO
    # Note: As this requires read-write access to your hard drive, # this will not run in the browser in Brython. def readFile(path): # This makes a very modest attempt to deal with unicode if present with open(path, 'rt', encoding='ascii', errors='surrogateescape') as f: return f.read() def writeFile(path, contents): with open(path, 'wt') as f: f.write(contents) contentsToWrite = 'This is a test!\nIt is only a test!' writeFile('foo.txt', contentsToWrite) contentsRead = readFile('foo.txt') assert(contentsRead == contentsToWrite) print('Open the file foo.txt and verify its contents.')