Module 3 · Arrays, Strings and Hashing · Lesson 7 of 40
Strings
Text as a row of characters: indexing, slicing, why strings can't change, and building them the fast way.
In this lesson · about 18 minutes
- Read characters and slices of a string
- Explain what immutable means and why += in a loop can be slow
- Build strings with a list and ''.join
A string is text, like "hello". It works like a list of characters: s[0] is "h", len(s) is 5, and s[1:4] is the slice "ell" (from index 1 up to, but not including, 4).
Strings can't be changed (immutable)
You cannot change one letter in place. s[0] = "j" is an error. Every "change" makes a new string. That is called being immutable.
This matters for speed. If you build a long string with result += letter inside a loop, Python may copy the growing string again and again. The fast habit is to collect the pieces in a list, then join them once at the end: "".join(pieces).
Handy string tools
| Code | Gives |
|---|---|
s.lower(), s.upper() | All small / all capital letters |
s.strip() | Removes spaces at the start and end |
s.split(" ") | A list of words |
"-".join(words) | One string with "-" between the words |
s[::-1] | The string reversed |
"ell" in s | True if "ell" appears in s (a search, O(n)) |
s.isalpha(), s.isdigit() | Only letters? Only digits? |
list(s) | A list of the characters (which you can change) |
Comparing two strings with == checks them letter by letter, so it is O(n) too.
Try it: string basics
Exercise
Is it a palindrome?
A palindrome reads the same forwards and backwards, like "level". Write is_palindrome(s) that returns True or False. Ignore capital letters: "Noon" counts.
Exercise
Count the vowels
Write count_vowels(s) that returns how many vowels (a, e, i, o, u, small or capital) are in the string.
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.