Creating strings and indexing
A string is written in quotes: 'Hi', "Hi", or '''many lines'''. Strings are immutable: s[0] = 'J' gives a TypeError.
Indexing: s = 'PYTHON' → s[0] = 'P', s[5] = 'N', s[-1] = 'N', s[-6] = 'P'. An index outside the range gives IndexError. len(s) = 6.
String operations: concatenation, repetition, membership, slicing
- Concatenation (+):
'Hi' + 'Ram'→ 'HiRam'. Both sides must be strings:'Age' + 16is a TypeError; usestr(16). - Repetition (*):
'ab' * 3→ 'ababab'. - Membership:
'TH' in 'PYTHON'→ True;'z' not in 'PYTHON'→ True. - Slicing s[start:stop:step]:
s[1:4]→ 'YTH',s[:3]→ 'PYT',s[3:]→ 'HON',s[::2]→ 'PTO',s[-3:]→ 'HON',s[::-1]→ 'NOHTYP'. Slices never raise IndexError; out-of-range parts are just left out.
Traversing a string
s = 'PYTHON'
for ch in s: # by character
print(ch, end=' ')
for i in range(len(s)): # by index
print(i, s[i])
i = 0
while i < len(s): # with while
print(s[i]); i += 1Counting vowels: v = 0; for ch in s.lower(): if ch in 'aeiou': v += 1.
Built-in string functions and methods
| Method | Example → result |
|---|---|
| len(s) | len('cat') → 3 |
| upper(), lower() | 'Hi'.upper() → 'HI' |
| title(), capitalize() | 'hello world'.title() → 'Hello World'; .capitalize() → 'Hello world' |
| count(sub) | 'banana'.count('a') → 3 |
| find(sub) / index(sub) | 'banana'.find('n') → 2; find gives −1 if missing, index gives ValueError |
| replace(old, new) | 'cat'.replace('c', 'b') → 'bat' |
| split(sep), join(list) | 'a b c'.split() → ['a', 'b', 'c']; '-'.join(['a', 'b']) → 'a-b' |
| strip(), lstrip(), rstrip() | ' hi '.strip() → 'hi' |
| startswith(), endswith() | 'python'.startswith('py') → True |
| isalpha(), isdigit(), isalnum() | 'abc1'.isalnum() → True; '12'.isdigit() → True |
| islower(), isupper(), isspace() | 'ABC'.isupper() → True |
| partition(sep) | 'a=b'.partition('=') → ('a', '=', 'b') |
None of these change s; they return a new value.
Board exam focus
Expect output questions on slicing and methods (1–2 marks) and programs: count vowels/uppercase/digits, check palindrome, reverse words, change case, replace characters (3 marks).
Key formulas and definitions
- Index: 0 … len−1 from left; −1 … −len from right
- s[start:stop:step] — stop excluded
- + join · * repeat · in membership
- Strings are immutable; methods return new strings
- find() → −1 if missing; index() → ValueError
Worked examples
1. s = 'COMPUTER'. Find s[2], s[-2], s[2:5], s[::-2].
s[2] = 'M'; s[-2] = 'E'; s[2:5] = 'MPU'; s[::-2] = 'RTPO' (indexes 7, 5, 3, 1).
2. Output? print('ab' * 2 + 'c', 'b' in 'abc', len('Hi there'))
ababc True 8
3. Count uppercase letters, lowercase letters and digits in 'Class11A'.
u = l = d = 0 for ch in 'Class11A': if ch.isupper(): u += 1 elif ch.islower(): l += 1 elif ch.isdigit(): d += 1 # u = 2, l = 4, d = 2
4. Check whether a string is a palindrome.
s = input().lower() if s == s[::-1]: print('Palindrome') else: print('Not palindrome') # 'Madam' → Palindrome
5. Output? s = 'hello world'; print(s.title(), s.find('o'), s.count('l'), s.replace('l', 'L', 1))
Hello World 4 3 heLlo world
6. Change the case of each letter (swap) without swapcase().
r = '' for ch in s: if ch.isupper(): r += ch.lower() else: r += ch.upper() # 'PyThOn' → 'pYtHoN'
7. Print each word of a sentence on its own line and the number of words.
w = 'I love Python'.split() for x in w: print(x) print(len(w)) # 3
Common mistakes
- Trying to change a character: s[0] = 'J'. Strings are immutable; build a new string instead.
- Expecting s[1:4] to include index 4.
- Joining a string and a number with +. Convert with str() first.
- Thinking upper() changes s. Write s = s.upper() to keep the result.