CMU 15-110: Principles of Computing
Strings: Part 2
- String Literals
- Newlines in strings
print('ab\ncd') # \n is a single newline character print(len('ab\ncd')) # 5 print('''ab cd''') - 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. '''
- Newlines in strings
- Some String Operators
- Slicing with default parameters
s = 'abcdefgh' print(s) print(s[3:]) print(s[:3]) print(s[:])
- Slicing with default parameters
- Some String Methods
- 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')) - 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('-------')
- String edits