🐍 Paper 2 · Topic 6: Programming
6.5 String Operations & Text Processing
Edexcel 1CP2 · GCSE Computer Science · ~11 min read · ✅ Free
Notes
──
Video
──
Slides
──
Worksheet
──
Quiz

Strings in Python

A string is a sequence of characters enclosed in quotes. Python strings are immutable — you cannot change individual characters; you create new strings instead.

name = "Alice" greeting = 'Hello, World!' multi = """This spans multiple lines"""

String Indexing and Slicing

Each character in a string has an index starting at 0. Negative indices count from the end.

word = "Python" # P y t h o n # idx: 0 1 2 3 4 5 # neg: -6 -5 -4 -3 -2 -1 print(word[0]) # P print(word[3]) # h print(word[-1]) # n (last character) print(word[1:4]) # yth (index 1 up to but NOT including 4) print(word[:3]) # Pyt (from start up to index 3) print(word[3:]) # hon (from index 3 to end) print(word[::-1]) # nohtyP (reversed)

Key String Methods

Method / FunctionWhat it doesExampleResult
len(s)Returns number of characterslen("Hello")5
s.upper()All characters to uppercase"hello".upper()"HELLO"
s.lower()All characters to lowercase"HELLO".lower()"hello"
s.strip()Removes leading/trailing spaces" hi ".strip()"hi"
s.replace(a,b)Replaces all occurrences of a with b"cat".replace("c","b")"bat"
s.find(sub)Returns index of first occurrence (-1 if not found)"hello".find("l")2
s.split(sep)Splits into a list at each separator"a,b,c".split(",")["a","b","c"]
sep.join(lst)Joins list items into a string",".join(["a","b","c"])"a,b,c"
s.count(sub)Counts occurrences of substring"hello".count("l")2
s.startswith(x)True if string starts with x"hello".startswith("h")True
s.endswith(x)True if string ends with x"hello".endswith("o")True
sub in sTrue if substring exists"ell" in "hello"True

String Concatenation and Repetition

first = "Hello" second = "World" combined = first + " " + second # "Hello World" (concatenation) repeated = "ha" * 3 # "hahaha" (repetition)

String / Integer Conversion

Strings and integers cannot be directly combined — you must convert:

age = 17 message = "You are " + str(age) + " years old" # str() converts int → string num_str = "42" number = int(num_str) # int() converts string → integer pi_str = "3.14" pi = float(pi_str) # float() converts string → float

Common String Processing Patterns

# Count vowels in a string text = "Hello World" count = 0 for char in text.lower(): if char in "aeiou": count += 1 print(count) # 3 # Check if a word is a palindrome word = "racecar" if word == word[::-1]: print("Palindrome!") # Validate a username (letters and digits only) username = input("Username: ") if username.isalnum() and len(username) >= 3: print("Valid username") else: print("Invalid: letters and digits only, min 3 chars")
Exam tip: String slicing is heavily tested. Remember: s[start:stop] — start is inclusive, stop is exclusive. s[1:4] gives characters at indices 1, 2, 3 (NOT 4). For the last character: s[-1] or s[len(s)-1]. String methods return new strings — they do NOT modify the original.
⚠️ Common Mistakes
  • Off-by-one in slicing — s[1:4] gives 3 characters (1, 2, 3), not 4
  • Forgetting strings are immutable — word[0] = "J" causes a TypeError; you must create a new string
  • Concatenating strings and integers without str() — "age: " + 17 causes a TypeError
  • Confusing .find() returning -1 (not found) with 0 (found at start)
  • Using = instead of == when checking string equality in an if statement
Video coming soon
Click slide or press arrow keys to navigate
✍️

Worksheet — 6.5 String Operations

8 Edexcel-style questions · instantly marked

Q1Given word = "Computing", state the output of: (a) word[0] (b) word[-1] (c) word[3:7] (d) len(word)[4]
✅ Mark scheme
(a) "C" [1] — index 0 is the first character; (b) "g" [1] — index -1 is the last character; (c) "puti" [1] — indices 3, 4, 5, 6 (stop 7 is excluded); (d) 9 [1] — "Computing" has 9 characters.
Q2Write Python code to: take a user's input, convert it to uppercase, and print only the first 5 characters.[3]
✅ Mark scheme
text = input("Enter text: ") [1]; text = text.upper() [1]; print(text[:5]) [1]. Accept equivalent correct answers e.g. print(text.upper()[:5]) combining steps.
Q3State the output of: "hello world".replace("world", "Python").upper()[2]
✅ Mark scheme
"HELLO PYTHON" [2] — first .replace("world","Python") gives "hello Python", then .upper() converts to "HELLO PYTHON". Award 1 mark for correct replace without upper.
Q4A program stores a full name as "John Smith". Write Python code to extract and print the first name and surname separately.[3]
✅ Mark scheme
full = "John Smith" [accept input]; parts = full.split(" ") [1]; first = parts[0] [1]; surname = parts[1] [1]; print(first, surname) or equivalent. Accept: using .find() to find space position, then slicing.
Q5Explain what this code does and state its output for text = "racecar": if text == text[::-1]: print("Palindrome") else: print("Not a palindrome")[3]
✅ Mark scheme
text[::-1] reverses the string [1]; it compares the original string to its reverse [1]; output: "Palindrome" because "racecar" reversed is still "racecar" [1].
Q6What error would occur with: name = "Alice"; print("Hello " + 42)? How would you fix it?[2]
✅ Mark scheme
TypeError — cannot concatenate a string and an integer directly [1]; fix by converting the integer to a string: print("Hello " + str(42)) [1]. Accept: using an f-string print(f"Hello {42}").
Q7Write a Python program that counts the number of vowels in a string entered by the user.[4]
✅ Mark scheme
text = input("Enter text: ") [1]; count = 0 [1]; for char in text.lower(): if char in "aeiou": count += 1 [1]; print(count) [1]. Must use loop [1], check membership in "aeiou" [1]. Note: using .lower() is good practice to handle uppercase vowels.
Q8Given csv_line = "Alice,17,A*", write code to extract and print each value separately. What data types are they?[4]
✅ Mark scheme
parts = csv_line.split(",") [1]; print(parts[0], parts[1], parts[2]) [1]; All three are initially strings [1] (even 17 comes out as "17" from split); to use 17 as an integer you need int(parts[1]) [1].
Topic Quiz
Q 1 of 15
You scored
out of 15
Click to reveal definition
🎉
Session complete!
TermDefinition
🎯

Mini Test — String Operations

Timed exam-style test — 10 minutes.

← 6.4c Dev LifecycleTopic 6 · PythonNext: 6.6 Project Guidance →