1

mrahmedcomputing

KS3, GCSE, A-Level Computing Resources

Lesson 5. String Handling


Lesson Objective

Understand the term String Handling and know how to use key exam functions.


Lesson Notes

Indexing

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!


Python String Handling Functions

There are several functions that you might have to use when developing algorithms. They are listed below:


Len()

Used to identity the amount of characters in a string. Can also be used to identity the amount of items in an array.

Code:

a = len(“Caterpillar”)
List = [“cat”,“hat”]
b = len(List)
print (a)
print (b)

Cmd Output:

11
2

Index Position

This function is used to return an index position of a character in a string or array.

Code:

the_string = “lovelace”
a = len(the_string)
b = the_string.index(“v”)
c = the_string.index(“l”)
print(a)
print(b)
print(c)

Cmd Output:

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”.

Code:

the_string = “lovelace”
d = the_string.index(“b”)
print(d)

Cmd Output:

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.


SUBSTRING

????

Code:

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]

Cmd Output:

love
vel
lace

The following method can be used to return a few characters on the left or right of the string.

Code:

the_string = “lovelace”
sub_right = the_string[-2:]
sub_left = the_string[:2]

print(sub_right)
print(sub_left)

Cmd Output:

ce
lo

Concatenation

Adding 2 strings together joins them. This process is called “Concatenation”.

Code:

name1 = “Mr ”
name2 = “Ahmed”
print (name1 + name2)
print (name2 + name1)

Cmd Output:

Mr Ahmed
AhmedMr 

.upper() and .lower()

To turn a string into all uppercase, use the upper function. To turn a string into all lowercase, use the lower function.

Code:

reptile = “Lizard”

print (reptile.upper())
print (reptile.lower())

Cmd Output:

LIZARD
lizard

ASCII Conversion

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)

Code:

asciiChar = chr(65)
asciiCode = ord(“e”)
print (asciiChar)
print (asciiCode)

Cmd Output:

A
101

3