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


  1. String Literals
  2. Some String Operators
  3. Some String Methods

  1. String Literals
    1. Newlines in strings
      print('ab\ncd') # \n is a single newline character print(len('ab\ncd')) # 5 print('''ab cd''')

    2. String Literals as Multi-line Comments
      ''' One way to 'comment out' a large block of code is to place it in triple-quotes. Python will basically ignore that code. '''

  2. Some String Operators
    1. Slicing with default parameters
      s = 'abcdefgh' print(s) print(s[3:]) print(s[:3]) print(s[:])

  3. Some String Methods
    1. String edits
      s.replace(old, new)Returns a copy of s replacing occurrences of old with new

      For example:
      print('This is nice. Really nice.'.replace('nice', 'sweet'))

    2. Substring search
      s.count(t)Returns number of times t occurs in s
      s.find(t)Returns the index of where t starts in s, or -1 if not there

      For example:
      print('This IS a history test'.count('is')) # 2 print('-------') print('Dogs and cats!'.find('and')) # 5 print('Dogs and cats!'.find('or')) # -1 print('-------')