Worksheets › Class 11 › Strings › Cheat sheet
Class 11 Strings: cheat sheet
CBSE Computer Science. Strings are immutable sequences of characters: indexing and slicing, joining, repeating and membership, traversal, and the string methods.
Key ideas
- Indexes run from 0 to len(s) − 1 from the left and from −1 backwards from the right; an index past the end is an IndexError, but a slice past the end just stops.
- s[a:b:c] takes characters from index a up to but not including b, in steps of c; s[::-1] gives the string reversed.
- Strings are immutable: s[0] = 'X' is a TypeError, and every method gives back a new string.
- + joins strings, * repeats one, and in and not in check whether one string is part of another.
- find() gives −1 when the text is not there, but index() raises a ValueError; count() counts occurrences that do not overlap.
- split() with no argument splits at runs of spaces into a list; join() puts a separator between strings; partition() gives a tuple of three.
- capitalize() makes only the first character a capital (the rest small); title() makes the first letter of every word a capital.
Remember
| 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 |
Watch out
- Including the stop index in a slice: 'computer'[2:5] has only three characters.
- Trying to change one character in place: build a new string instead.
- Expecting find() to raise an error, or index() to give −1.
- Forgetting that a space is a character and counts in len().
Worked example
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
Practise Strings
Revise with this page, then practise: every Strings sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.