Wednesday 1 July 2015

11. Data types: string manipulation and string methods


You will learn:
  • To use strings
  • To use index positions in strings
  • To slice strings


Activity 10.1
Strings
Write the index position for each character in the string.
H
e
l
l
o

w
o
r
l
d
!













What character is at index 3?
What character is at index 5?
What character is at index 0?
What character is at index 11?
How many characters are there in this string?
Activity 10.2
Use the interactive shell to explore how strings can be concatenated.
Make a variable called FirstName and set its value to the string “Fred
Make a variable called SecondName and set its value to the string “Smith”
Make a variable called FullName and set its value to the value of the variablesFirstName plus SecondName
Print the value of the variable FullName

Activity 10.3
Slicing strings
Parts of a string can be extracted (or sliced) by giving the index location in the format:
[start position: end position]

Start position is the index at which the slice starts (remember that indexing starts at zero).End position is the index AFTER the last index required.

Use the interactive shell to explore how strings can be sliced.

Make a variable called word and set its value to the string “PIZZA”.

>>>word="PIZZA"

P
I
Z
Z
A
0
1
2
3
4

 
What do these commands do?

o
>>>word[2:5]
o
>>>word[1:2]
o
>>>word[0:3]
o
>>>word[0:5]

Hint: Remember that the index starts at zero not one.
Activity 10.4
A variable has been created and assigned the string “watch #bbcclick today”

myVariable = “watch #bbcclick today”

w
a
t
c
h

#
b
b
c
c
l
i
c
k

t
o
d
a
y
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

What command would you use to extract the following slices?

o
#bbcclick
o
watch
o
today

Check your answers using the interactive shell.
Activity 10.5
Using string methods
Any variable with a string assigned is a member of the class called string. String methods can be used to manipulate that string.
Explore string methods by working through these commands in the interactive shell and describing what happens.

>>>myVariable="There's a starman waiting in the sky"
>>>myVariable.upper()
>>>myVariable.replace("a","x")
>>>myVariable.title()
>>>myVariable.swapcase()
Activity 10.6
The string .format method revisited: using the string .format method to format output
There are two ways to output information to the screen. Using the print() function or by giving the expression.

Try these now:
>>>myName="David Bowie"
>>>print(myName)
David Bowie

 >>>myName
'David Bowie'

The string .format is used to give more control over formatting.

It allows you to use placeholders and then specify the variable you want to print in the string. The placeholders are shown using {}.

>>>first="David"
>>>second="Bowie"
>>>print("The best music is from {0}       {1}!".format(first,second))

The best music is from David       Bowie!

It also allows you to choose how to format the output.

No comments:

Post a Comment