String Manipulation
A string is a sequence of characters — anything you can type: letters, digits, spaces and symbols such as commas, dashes or exclamation marks. Every piece of text a program holds is a string, even something that looks like a number such as "07700 900123", because the quote marks make it text rather than a value to do arithmetic with.
Strings turn up everywhere: a player name on a scoreboard, an answer typed at an input() prompt, a message printed to the screen. The characters are kept in order, so a string can be counted, copied in part or rebuilt.
String manipulation means working with the characters inside a string instead of treating the whole thing as one lump. A program rarely wants text exactly as it was typed — it may need to count the characters, pull out part of a code, glue two names together, ignore capital letters or turn a letter into its code.
| Task | Tool |
|---|---|
| Count the characters | len() |
| Pick out one character | [i] |
| Copy out part of the string | [start:end] |
| Join strings end to end | + |
| Switch between capitals and lowercase | .upper() and .lower() |
| Swap a character for its code, and back | ord() and chr() |
| Visit every character in turn | a loop |
Python has many more string methods, such as split(), replace(), find() and count(). These are not required here and questions will not depend on them, because the same jobs — counting how often a letter appears in a word, checking whether a booking reference contains a certain letter, or building a display label from parts of a title — can be done with the tools in the table.
# a string can hold letters, digits, spaces and symbols
fixture = "Match 3: Kestrels vs Hawks!"
print(fixture)
print(len(fixture))
print(fixture.upper())Output:
Match 3: Kestrels vs Hawks!
27
MATCH 3: KESTRELS VS HAWKS! OCR GCSE Computer Science · String Manipulation