[Tutor] integer

Kirby Urner urnerk@qwest.net
Sun, 9 Jun 2002 18:21:04 -0400


On Sunday 09 June 2002 08:17 pm, Ricardo Ortega wrote:
> How can I get an integer from a string example: =91BLK 15423 L=92
> How can I get just the integer from that string if I didn=92t know what=
 it
> looked like before hand all I new is that there was a number somewhere
> in the string.

Hi Ricardo:

Import the regular expression (regexp) module, named re:

>>> import re

Then compile a search pattern.  The one below looks for any string of one=
 or
more digits.  You only need to compile this pattern once, then use it ove=
r and
over.

>>> srch =3D re.compile("[0-9]+") =20

Now here's a short function that uses the search method of the srch objec=
t
(created by your re.compile()).  If it gets a result, it'll return the
matching segment, otherwise it returns the empty string.

>>> def getstr(thestr):
=09m =3D srch.search(thestr)
=09if m:  return m.group()
=09else:  return ''

Here it is in action:
=09
>>> getstr("BLK 15423 L")
'15423'

Another example:

>>> getstr("RRS 44523LL 12P")
'44523'

As written, we're only picking up the first match in the string, but=20
with tweaks could get them all.

You can adapt the above for your own purposes.

For a lot of interesting reading on regular expressions in Python, see:
http://py-howto.sourceforge.net/regex/regex.html

Kirby

PS:  instead of "[0-9]+" as the pattern, you could use "\d+" and get
the same result, as \d means the same as [0-9] i.e. "any decimal digit".