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

(singke) #1
value that the input() function returns. If the string contains an invalid digit, the
script produces a message telling the user about the error:
Click here to view code image
pi@raspberry script% python3 script1001.py
Please enter your age: 34
Your age is 34
pi@raspberry script% python3 script1001.py
Please enter your age: Rich
Sorry, that is not a valid age
pi@raspberry script% python3 script1001.py
Please enter your age: 12g5
Sorry, that is not a valid age
pi@raspberry script%
You can also try using the other string-testing functions in the same manner to see
how they validate different types of text that you enter from the prompt.

Searching Strings


Yet another common string function is searching for a specific value within a string. Python provides
a couple functions to help out with this.


If you only need to know if a substring value is contained within a string value, you can use the in
operator. The in operator returns a True value if the string contains the substring value, and it
returns a False value if not. Here’s an example:


Click here to view code image


>>> string12 = 'This is a test string to use for searching'
>>> 'test' in string12
True
>>> 'testing' in string12
False
>>>

If you need to know exactly where in a string the substring is found, you need to use either the
find() or rfind() functions.


The find() function returns the index location for the start of the found substring, as shown here:


>>> string12.find('test')
10
>>>

The result from the find() function shows that the string 'test' starts at position 10 in the string
value. (Strings start at index position 0 .) If the substring value isn’t in the string, the find() function
returns a value of -1:


Click here to view code image


>>> string12.find('tester')
-1
>>>

The find() function searches the entire string unless you specify a start value and an end value to
define a slice, as in this example:


Click here to view code image

Free download pdf