[Tutor] finding a number with str.find

Alan Gauld alan.gauld at btinternet.com
Mon Oct 8 19:07:38 CEST 2012

On 08/10/12 17:33, Benjamin Fishbein wrote:
> Is there a way to find the next character that is a digit (0-9) in a string?
 > it seems that the str.find method can only find one particular 

When looking for patterns rather than literal values you need to use 
regular expressions. These can get very complex very quickly but 
searching for a number is not too bad. One simple way (although
not optimal) is to put the characters you want inside square brackets

 >>> import re
 >>> s = "a string with 7 words in it"
 >>> res = re.search("[0-9]", s)
 >>> res.group()

This returns something called a match object which can tell you what was 
found. You can then use that to find the index in the string.

 >>> s.index( res.group() )

Having digits in a search pattern is such a common thing that there
is a special syntax for that - '\d' :

 >>> s.index( re.search("\d", s).group() )

Finally you can find all occurrences of a pattern in a string using 
re.findall() which returns a list of the found matches:

 >>> re.findall("\d",s)   # only one occurrence in this case...

you can then loop through the results to locate each item.

Regular expressions are way more powerful than this and there can be a 
tendency to overuse them. This should be resisted since they can 
introduce very hard to find bugs due to subtle errors in the patter 

You can find a very gentle introduction to their other features in the 
re topic of my tutorial.


Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list