Skip to content

Class 11 · Computer Science · Computer Science

Chapter 8: Strings Notes

The big idea

A string is an immutable sequence of characters that can be indexed, sliced, joined, repeated, traversed and processed with many built-in methods.

Things to remember

  • A string is a sequence of Unicode characters in single, double or triple quotes; triple quotes allow several lines. Python has no separate character type: a one-letter string is a character.
  • Indexing: the first character has index 0 and the last n - 1; negative indices run from -1 (last) to -n (first). For 'Hello World!' of length 12, s[6] is W and s[-1] is !. An index out of range gives IndexError; a float index gives TypeError.
  • Strings are immutable: s[1] = 'a' raises a TypeError, because a string cannot be changed after creation. To get a changed string, build a new one, for example with replace(), which returns a new string.
  • Operations: + concatenates, * repeats ('Hello' * 2 is HelloHello), in and not in test for a substring ('Wor' in 'Hello World!' is True). None of these change the original string.
  • Slicing s[n:m] gives characters from index n up to m - 1, so s[1:5] is ello. s[:5] is Hello, s[6:] is World!, s[0:10:3] is HlWl with step 3, and s[::-1] reverses the string. If n is greater than m, the result is an empty string.
  • To traverse a string, use for ch in s, or a while loop with an index that runs from 0 while index is less than len(s). The built-in len() returns the number of characters.
  • Methods: upper(), lower(), title(), count(), find() (returns -1 if not found), index() (raises ValueError if not found), startswith(), endswith(), isalnum(), strip(), replace(), join(), partition() and split(). Exam tip: remember find versus index.
  • Typical programs: count a character, replace vowels with *, reverse a string, and check for a palindrome (a string equal to its reverse, like kanak) by comparing characters from both ends.

Words to know

Tap a card to see what it means

Quick quiz

⭐ 0 / 5
  1. For s = 'Hello World!', what is s[1:5]?

  2. For s = 'Hello World!', what is s[-6:-1]?

  3. For s = 'Hello World!', what is s[0:10:3]?

  4. Assertion (A): The statement s[1] = 'a' on a string s causes a TypeError. Reason (R): Strings in Python are immutable. Which is correct?

  5. For t = 'Hello World! Hello Hello', which statement is true?

Match the pairs

Match each string operation with its result for s = 'Hello World!'.

Try this at home

Choose five words, including kanak and level, and test each one by reading it backwards on paper. Sort them into palindromes and non-palindromes, then check one with s == s[::-1] in an online Python shell with an adult.

All Computer Science notesChapter page and exercisesComputer Science syllabus