MS1008-Tutorial 5
MS1008-Tutorial 5
MS1008
Week 5
Accessing Strings
A string is a sequence of characters.
It is indicated using single quote (‘…’) or double quotes (“…”).
Index and slicing:
We can use [ ] to access particular characters in a string.
Basic Operations
Membership Operation
Methods for Strings
A method is a variation on a function.
- It represents a program.
- It has input arguments and output.
Unlike a function, it is applied in the context of a particular object.
- This is indicated by the dot notation invocation.
Each string is itself an object
It will output a new string, which is the same as the string on which it was called, except
all letters will now be in upper case.
Study the Python methods associated with string, and write down the
expressions for doing the following, given the string "it's a beautiful
day." (Not all functions have been covered in class.)
i. Capitalize the first word
ii. Capitalize each word
iii.Convert the whole string to upper case
iv.Remove all the spaces
v. Count the number of a specific character in the string
Solution to Problem 3 (optional)
Study the Python methods associated with string, and write down the
expressions for doing the following, given the string "it's a beautiful
day." (Not all functions have been covered in class.)
S1 = "it's a beautiful day."
i. Capitalize the first word
S2 = S1.capitalize()
print(S2)
ii. Capitalize each word
S2 = S1.title()
print(S2)
iii.Convert the whole string to upper case
S2 = S1.upper()
print(S2)
iv.Remove all the spaces
S2 = S1.replace(" ", "")
print(S2)
v. Count the number of a specific character in the string
print(S1.count("a"))