7.10. Parsing strings

Often, we want to look into a string and find a substring. For example if we were presented a series of lines formatted as follows:

From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008

and we wanted to pull out only the second half of the address (i.e., uct.ac.za) from each line, we can do this by using the find method and string slicing.

First, we will find the position of the at-sign in the string. Then, we will find the position of the first space after the at-sign. Finally, we will use string slicing to extract the portion of the string which we are looking for.

Activity: CodeLens 7.10.1 (strParsing)

We use a version of the find method which allows us to specify a position in the string where we want find to start looking. When we slice, we extract the characters from one beyond the at-sign through up to but not including the space character.

The documentation for the find method is available at

https://docs.python.org/library/stdtypes.html#string-methods.

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

You have attempted 1 of 4 activities on this page