Python For GCSE
Handling Strings
Strings Are Lists Of Characters
Strings are lists of character data. We can use the index of these characters to access parts of a string separately.
name = "Ozymandias" for i in range(len(name)): print(name[i])
We can loop through a string without using a counting loop.
name = "Ozymandias" for n in name: print(n)
Contains
The keyword in allows us to check if a string contains another string - or not.
name = "Ozymandias" if "man" in name: print("Contains man.") if "chips" not in name: print("Does not contain chips")
Case Conversion
We can change the case of a string,
name = "Ozymandias" low = name.lower() up = name.upper() print(low,up)
ASCII Numbers
We can turn ASCII numbers into characters using the chr() function and get the ASCII number of a character using the ord() function.
for i in range(65,70): c = chr(i) print(c) for c in "abcde": asc = ord(c) print(asc)
Other Useful String Methods
The following all assume a string defined using the variable name txt.
Function | Returns | Example |
---|---|---|
capitalize() | The string with the first letter converted to upper case. | t = txt.capitalize() |
center() | The string centred. | t = txt.center(10) t = txt.center(10,"*") |
endswith() | True or false. | tion= txt.endswith("tion") |
find() | The index of a substring of a string or -1 if not found. | i = txt.find("dis") |
isalnum() | True if all characters in the string are alphanumeric. | alphanum = txt.isalnum() |
isalpha() | True if all characters in the string are letters. | alpha = txt.isalpha() |
isdigit() | True if all characters in the string are digits. | dig = txt.isdigit() |
islower() | True if all characters in the string are lower case. | low = txt.islower() |
isupper() | True if all characters in the string are upper case. | up = txt.isupper() |
join() | Joins the elements of a list into a single string using the given separator. | s = ",".join(mylist) |
lstrip() | Removes spaces from the left side of a string. | t = txt.lstrip() |
replace() | Replaces part of a string with a specified string. | t = txt.replace("him", "her") |
rstrip() | Removes spaces from the right side of a string. | t.txt.rstrip() |
split() | Splits a string into a list using a specified separator. | mylist = txt.split(",") |
startswith() | True or false. | tion= txt.startswith("re") |
strip() | Removes whitespace from the beginning and end of a string. | t = txt.strip() |
title() | The string converted to title case. | t=txt.title() |