5 String Manipulation

String Index

String index starts at “0”. The is how the sentence “Hello world” would be indexed

1
2
3
4
5
6
7
8
9
10
sentence="Hello world"

a=sentence[6]
print(a)

b=sentence[0]
print(b)

c=sentence[9]
print(c)

Length Capital letters and lowercase

1
2
3
4
5
6
7
8
9
month="August"

a=month.lower()
print(a)
b=month.upper()
print(b)

c=len(month)
print(c)

Slicing Strings

Copy and paste the code below into an editor E.g. IDLE and run. Experiment by changing the code and predicting what the result will be

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
phrase = "Hello world"

first_5_letters = phrase[0:5]
#[Hello ] world
print(first_5_letters)

letters_2_thru_4 = phrase[1:4]
#H[ell]o world
print(letters_2_thru_4)

letter_5_to_end = phrase[4:]
#Hell[o world]
print(letter_5_to_end)

first_3_letters = phrase[:3]
#[Hel]lo world
print(first_3_letters)

copy_of_string = phrase[:]
#[Hello world]
print(copy_of_string)

Quiz

All characters lower case

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
phrase = "computer science"

a = phrase[0:5]
print(a)

b = phrase[1:4]
print(b)

c = phrase[4:]
print(c)

d = phrase[:3]
print(d)

e = phrase[:]
print(e)

Casting from string to integer

We need to cast from string data to integer so we can do addition

Copy and paste this into Python and experiment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
number="123456"

#get the positions of the numbers
a=number[0]
b=number[1]
c=number[2]

#cast the number to an integer
   
a1= (int(a))
b1= (int(b))
c1= (int(c))

#now you can do maths
total=(a1+b1+c1)
print(total)