Lesson Objective
Understand the term String Handling and know how to use key exam functions.
KS3, GCSE, A-Level Computing Resources
To refer to just one item in the list, you would refer to its index position. Each item is given a number. The first item is referred to as position "0".
The same indexing method can be used on strings as well.
PICTURE!
There are several functions that you might have to use when developing algorithms. They are listed below:
Used to identity the amount of characters in a string. Can also be used to identity the amount of items in an array.
a = len(“Caterpillar”) List = [“cat”,“hat”] b = len(List) print (a) print (b)
11 2
This function is used to return an index position of a character in a string or array.
the_string = “lovelace” a = len(the_string) b = the_string.index(“v”) c = the_string.index(“l”) print(a) print(b) print(c)
8 2 0
the_string (variable/data) is selected. The character “v” is looked for in the string; the index position is then stored in the variable “b”.
the_string = “lovelace” d = the_string.index(“b”) print(d)
Traceback (most recent call last):
File "/tmp/sessions/092fa9fca/main.py", line 2, in module
print(a.index("d"))
ValueError: substring not found
An error will be returned if you search for an item that in not in a string or array.
????
the_string = “lovelace” sub1 = the_string[0:4] sub2 = the_string[2:5] sub3 = the_string[4:-1] print(sub1) print(sub2) print(sub3) #[startIndex:endIndex-1]
love vel lace
The following method can be used to return a few characters on the left or right of the string.
the_string = “lovelace” sub_right = the_string[-2:] sub_left = the_string[:2] print(sub_right) print(sub_left)
ce lo
Adding 2 strings together joins them. This process is called “Concatenation”.
name1 = “Mr ” name2 = “Ahmed” print (name1 + name2) print (name2 + name1)
Mr Ahmed AhmedMr
To turn a string into all uppercase, use the upper function. To turn a string into all lowercase, use the lower function.
reptile = “Lizard” print (reptile.upper()) print (reptile.lower())
LIZARD lizard
These functions are used to turn ASCII characters to ASCII code, and ASCII code to ASCII character. To convert between characters and their ASCII codes, use the function CHR and ASC (ORD in Python)
asciiChar = chr(65) asciiCode = ord(“e”) print (asciiChar) print (asciiCode)
A 101