Strings are immutable sequences of characters: indexing and slicing, joining, repeating and membership, traversal, and the string methods.
| s = 'computer' | s[0] = 'c', s[-1] = 'r', s[2:5] = 'mpu', s[:3] = 'com', s[::2] = 'cmue' |
| Reverse and length | s[::-1] = 'retupmoc'; len(s) = 8 |
| Searching | 'banana'.count('a') = 3; 'banana'.find('n') = 2; 'banana'.find('z') = −1 |
| Changing | 'banana'.replace('a', 'o') = 'bonono'; ' hi '.strip() = 'hi' |
| split and join | 'to be or'.split() = ['to', 'be', 'or']; '-'.join(['a', 'b']) = 'a-b' |
| partition() | 'a,b,c'.partition(',') = ('a', ',', 'b,c') |
| Case | 'my BOOK'.capitalize() = 'My book'; 'my BOOK'.title() = 'My Book' |
| Tests | 'abc1'.isalnum() is True; 'abc1'.isalpha() is False; '42'.isdigit() is True |
What does this program print? Give (a) the first line (b) the second.
s = 'science'
print(s[:-4])
print(s[::-1])
Working: index: s0 c1 i2 e3 n4 c5 e6
Answer: (a) sci; (b) ecneics