Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
10327 views
ubuntu2004
Kernel: Python 3 (system-wide)

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.

Run the code below to see how this works.
sentence = 'Hello, world!' # Find the index of the character '!' in the variable sentence and assign it to the variable called idx. idx = sentence.find('!') print( f'"!" is at index {idx}' ) # Find the index of the substring 'world' in the variable sentence. idx = sentence.find('world') print( f'"world" begins at index {idx}' )
"!" is at index 12 "world" begins at index 7

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:

# Find the index of the substring 'today' in the variable sentence. idx = sentence.find('today') print( idx )
-1

Converting a string to lowercase

Here is an example in which we convert all the letters in a string to lowercase.

Run the following code to see how to convert all letters in a string to lowercase.
name = 'HARRY POTTER' # The lower() method returns a string converted to lowercase. lowercase_name = name.lower() print(lowercase_name)
harry potter

A full list of string functions and methods is available in the Python 3 documentation.

Exercise Notebook

Next Notebook