Extracting int from string

Spencer Ernest Doidge spencer at efn.org
Mon Jan 13 18:27:38 EST 2003


ooo I like this one. Thanks everybody. Mikael gets today's cool snippet 
du jour award from my station.

Spencer Doidge

On Mon, 13 Jan 2003, [iso-8859-15] Mikael Schönenberg wrote:

> 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