Extracting int from string

Mikael Schönenberg micke at strakt.com
Mon Jan 13 23:38:06 CET 2003


On 13 Jan 2003, Spencer Ernest Doidge wrote:

> What would be the best way to extract the integer value 45 from the following string?
>
> 'X=   45   A'

Depending on exactly what the general format of the string is, this might
be what you want:

>>> int(''.join([c for c in 'X=   45   A' if c in '0123456789']))
45

Or, possibly less obscure (untested though):

startStr = 'X=   45   A'
intsInStr = []
for c in startStr:
  if c in '0123456789':
    intsInStr.append(c)
intStr = ''.join(intsInStr)
finalInt = int(intStr)
print finalInt
^^^^^^^^^^^^^^
Should hopefully result in 45 :)

Untested, and... ehrm... with room for optimisation ;)

/micke






More information about the Python-list mailing list