- Home
- Lessons
- GCSE & IGCSE Computer Science
- Manipulating strings
Manipulating strings
🎬 The doodle video for this lesson is coming soon. Subscribe on YouTube to see it first.
Usernames, passwords and messages are all strings. Python gives you tools to measure, slice and change them.
Length and position
len(word) gives the number of characters.
Characters are numbered from 0. If word = "Python", word[0] is "P" and word[5] is "n".
word[-1] is the last character.
word.find("h") gives the position of the first "h": 3. It gives -1 if not found.
Characters are numbered from 0. If word = "Python", word[0] is "P" and word[5] is "n".
word[-1] is the last character.
word.find("h") gives the position of the first "h": 3. It gives -1 if not found.
Substrings (slicing)
word[start:end] gives the characters from start up to, but not including, end.
"Python"[0:3] is "Pyt". "Python"[2:] is "thon".
"Python"[0:3] is "Pyt". "Python"[2:] is "thon".
Case conversion and joining
word.upper() gives "PYTHON". word.lower() gives "python".
Compare in one case so "YES", "Yes" and "yes" are all accepted: if answer.lower() == "yes":
Join strings with +: "Py" + "thon" gives "Python".
Compare in one case so "YES", "Yes" and "yes" are all accepted: if answer.lower() == "yes":
Join strings with +: "Py" + "thon" gives "Python".
Make a username from the first 3 letters of "Amelia" and her birth year 2010.
- "Amelia"[0:3] = "Ame"
- str(2010) = "2010"
- Join with +
Answer: Ame2010
len() counts characters. Positions start at 0. word[a:b] gives a substring up to but not including b. upper() and lower() change case; + joins strings.
Check you have got it
Answer 6 quick questions with instant marking. If you get one wrong, GCSE-ready shows you why and gives you another go. It is free, and you do not need an account.