Login

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?

Please register to read more ......