Extracting int from string
Thomas Boettcher
boettcher at rz.rwth-aachen.de
Tue Jan 14 04:28:13 EST 2003
hi spencer,
>>On 13 Jan 2003, Spencer Ernest Doidge wrote:
>>>'X= 45 A'
> On Mon, 13 Jan 2003, [iso-8859-15] Mikael Sch?nenberg wrote:
>>>>>int(''.join([c for c in 'X= 45 A' if c in '0123456789']))
micke's code just cuts out all non-digits and presents the int of the
remainder. so 'X= 45 A 32' for example would produce 4532 - if
thats what you want.
maybe you want something like this:
# importing regular expressions module
import re
# regular expression to find the first number in a string
reObj = re.compile('\D*(\d+)')
# producing your answer
answer = int( reObj.match('X= 45 A').group(1) )
the reObj has to be compiled once but can be used at multiple locations
in your program.
if your string does not contain a number this will throw an
AttributeError since the reObj.match will be None.
have fun
tomtom
--
++ Thomas Boettcher Computing and Communication Center ++
++ office: 2.35 University of Technology Aachen ++
++ phone: +49 (241) 80-29205 Seffenter Weg 23 ++
++ mailto:boettcher at rz.rwth-aachen.de 52074 Aachen, Germany ++
More information about the Python-list
mailing list