ubuntu2004
Strings III - manipulating and interrogating strings with string methods
There are a many ways in Python to manipulate and interrogate strings; these are called string methods. There are far too many to cover in this course. We will look at a couple now, which we will use in the course, and you can google others as they become necessary.
A method is applied to a string or string variable by using dot notation after the string or string variable.
Getting the index of a character or substring
In the last Notebook we used indicies to access characters and substrings within a string. We can also do the opposite and find the index of a character or substring within a string. We use the method find()
to get the index of the first occurrence of a substring.
If the character or substring we're searching for doesn't exist within the string then find()
returns -1 as shown in the following code:
Converting a string to lowercase
Here is an example in which we convert all the letters in a string to lowercase.
A full list of string functions and methods is available in the Python 3 documentation.