Back

String methods

A string in Python is an 'object'. Because it is an object, we can do a lot of different things to it. We can apply 'methods' to a string object. Applying a method is also known as 'invoking' a method. A 'method' is similar to a function. It simply performs some action on a particular object. To invoke a method on an object, you need to know what object you are using and what method you want to invoke. We do this using the dot notation. Consider this:

myWord = "Hello"
print(myWord.lower())

This prints out 'hello'. There is a string object myWord, then a full stop, then the method I want to use, then some brackets, which in this case doesn't contain anything. Some methods need data (known as 'arguments') so it can work, or you will get an error. Some methods don't need any arguments at all. 

To be able to use string methods, you need to know what methods are available. You can always search the Internet for 'Python string methods' to get a list and a description of how they work. If a method isn't available that you want to use, you can always write a function and use that instead!

Q1. Get the following code working:

1.    myWord = "Battleships and cabbages"
2.    print(myWord.lower())
3.    print(myWord.upper())
4.    print(myWord.find('s'))
5.    print(myWord.count('a'))

Q2. What would you expect to happen if you used double quotes in line 4?

4.    print(myWord.find("s"))

Q3. What would you expect to happen if you searched for the substring bag in line 4?

4.    print(myWord.find('bag'))

Q4. I've added an extra line to the original program:

1.    myWord = "Battleships and cabbages"
2.    print(myWord.lower())
3.    print(myWord.upper())
4.    print(myWord.find('s'))
5.    print(myWord.count('a'))
6.    print(myWord.replace('t','x')

Can you guess what the output will be before running it. Run the code to see if you were right.
Q5.
Write a line of code to change every instance of the letter a so it is a capital A.
Q6.
Write a line of code so that capital letters are changed to lower case letters and lower case letters are changed to capital letters.
To do this, you will have to search for 'Python string methods' and see if you can find a method you can use that will do the job.
Q7. Write a line of code so that you print the myWord string so that it is left hand justified, exactly 30 characters long and any padding you need to get it to be exactly 30 characters long is done using a capital V.
Q8. Write the following code in Python:

test = 'Hello'
test.

After the dot, wait a second and a drop-down list of all the string methods will appear. Explore them. Select some of them. Try them out. Search Google or the Python documentation for the methods you want to use to get further information, help and examples.

Q9. There isn't a method for reversing a string. Write and test a program to do that in Python.

Back