Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
>>> string12.find('test', 12, 20)
-1
>>>

It’s also important to know that the find() function returns only the location of the first occurrence
of the substring value, like this:


Click here to view code image


>>> string13 = 'This is a test of using a test string for searching'
>>> string13.find('test')
10
>>>

You can use the rfind() function to start the search from the right side of the string:


>>> string13.rfind('test')
26
>>>

Yet another searching function is the index() function. It performs the same function as find(),
but instead of returning -1 if the substring isn’t found, it returns a ValueError error, as shown
here:


Click here to view code image


>>> string13.index('tester')
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
string13.index('tester')
ValueError: substring not found
>>>

The benefit of retuning an error instead of a value is that you can catch the error as a code exception
(see Hour 17, “Exception Handling”) and have your script act accordingly.


If you’d like to just count the number of occurrences of a substring value within a string, you use the
count() function, as shown here:


>>> string13.count('test')
2
>>>

Between the find(), index(), and count() functions, you have a full arsenal of tools to help
you search for data within your strings.


Formatting Strings for Output


Python includes a powerful method of formatting the output that your script displays. The format()
function allows you to declare exactly how you want your output to look. This section walks through
how the format() function works and how you can use it to customize how your script output
looks.


Watch Out!: Python Change in String Formatting
The way Python defines formatting codes for the format() function drastically
changed between version 2 and 3. Since this book focuses on Python v3, we only cover
Free download pdf