Edexcel International Advanced Level Computer Science, point 8.2.2
A string is a sequence of characters. You must be able to select and use appropriate methods for handling string data. (Check the PLS for the exact methods allowed.) Strings in Python are immutable: methods return a new string and don't change the original.
a. Length
len() gives the number of characters (including spaces and punctuation).
word = "computer"
print(len(word)) # 8
print(len("")) # 0
b. Indexing
Each character has a position (index), starting at 0. Negative indices count from the end.
word = "computer"
print(word[0]) # c (first)
print(word[3]) # p
print(word[-1]) # r (last)
print(word[len(word) - 1]) # r
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Char | c | o | m | p | u | t | e | r |
| Negative | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
- Going past the end is an
IndexError. - Strings can't be changed by index:
word[0] = "C"is aTypeError.
Slicing
s[start:stop] gives characters from start up to but not including stop.
print(word[0:3]) # com
print(word[3:]) # puter
print(word[:4]) # comp
print(word[::-1]) # retupmoc (reversed)
print(word[::2]) # cmue (every second)
c. Formatting
Controlling how values appear in text.
name = "Amy"
mark = 87.456
print(f"{name} scored {mark:.1f}") # Amy scored 87.5
print(f"{mark:8.2f}|") # width 8, 2 decimals
print(f"{name:>10}|") # right-aligned in 10
print(f"{name:<10}|") # left-aligned
print(f"{5:03d}") # 005 (zero-padded)
print("Total: " + str(12) + " items") # joining with str()
print("{} is {} years".format("Raj", 17))
- f-strings (
f"...") put values inside{}, with a format after a colon. .2fis 2 decimal places,>10right-aligns in a width of 10,03dpads with zeros.- Joining (
+) needs strings, so convert numbers withstr(). ^centres a value in its width, as<and>align it left and right.
Laying out a table with fixed widths, so the columns line up:
items = [("Pen", 3, 0.5), ("Notebook", 2, 2.25), ("Ruler", 1, 1.2)]
print(f"{'Item':<10}{'Qty':^5}{'Price':>8}")
for name, qty, price in items:
print(f"{name:<10}{qty:^5}{price:>8.2f}")
Output:
Item Qty Price
Pen 3 0.50
Notebook 2 2.25
Ruler 1 1.20
d. Examining
Finding out about a string without changing it.
text = "Hello, World"
print(text.upper()) # HELLO, WORLD
print(text.lower()) # hello, world
print(text.find("World")) # 7 (index of first match, or -1)
print(text.count("l")) # 3
print("World" in text) # True
print(text.startswith("Hello")) # True
print(text.endswith("!")) # False
print("abc123".isalnum()) # True
print("123".isdigit()) # True
print("abc".isalpha()) # True
print(" ".isspace()) # True
print("hello world".capitalize()) # Hello world (first letter only)
print("ABC".isupper()) # True
print("abc".islower()) # True
print("2026".isnumeric()) # True
print(text.index("o")) # 4 (error if not found)
Character codes: ord("A") is 65, chr(66) is "B" (2.3.1).
e. Manipulating
Making a new string from an existing one.
s = " data science "
# 'data science' (remove spaces both ends)
print(s.strip())
print("a,b,c".split(",")) # ['a', 'b', 'c']
print("-".join(["a", "b", "c"])) # a-b-c
print("cat".replace("c", "b")) # bat
print("hi" * 3) # hihihi
print("title case".title()) # Title Case
print("Hello"[1:4]) # ell
print("abc" + "def") # abcdef
print("42".zfill(5)) # 00042
Building a string in a loop
word = "stressed"
reversed_word = ""
for ch in word:
reversed_word = ch + reversed_word
print(reversed_word) # desserts
Worked example
Task: write code that checks whether a word is a palindrome, ignoring case and spaces, and creates initials from a full name.
def is_palindrome(text):
cleaned = text.replace(" ", "").lower() # manipulate
return cleaned == cleaned[::-1] # compare to reversed
def initials(full_name):
parts = full_name.split() # split into words
return "".join(p[0].upper() for p in parts)
print(is_palindrome("Never odd or even")) # True
print(initials("amy louise lee")) # ALL
is_palindrome("Never odd or even"): remove spaces and lower-case toneveroddoreven, which reads the same backwards.initials:split()gives["amy", "louise", "lee"],p[0]is the first character,.upper()capitalises, andjoincombines them.
Exam tip: remember indexing starts at 0, slices exclude the end, and string methods return new strings (strings can't be changed in place). Use len() for the length, and s[::-1] to reverse. Know the difference between find (returns -1) and index (raises an error).
Check yourself
What is "computer"[2:5]?
"mpu" (indices 2, 3 and 4).
What does "a-b-c".split("-") return?
The list ["a", "b", "c"].
Why does word[0] = "C" cause an error?
Strings are immutable, so a character can't be changed in place; you must build a new string.
How do you display 2.71828 to 2 decimal places in an f-string?
f"{2.71828:.2f}", which gives 2.72.
What does "Hello".find("z") return?
-1, because it isn't found.