Extracting int from string

Peter Hansen peter at engcorp.com
Mon Jan 13 17:28:23 EST 2003


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

You haven't provided nearly enough for a general answer.  The answer to "best"
depends on a lot of things.

What is important in your string?  The number of spaces before and after the 45?
The fact that there are spaces there at all?  Spaces, or any whitespace?  What
is the "A"... a single character?  A word?  The rest of the line?

Is the "X=" always going to come first?  Or could it be anything before the
equal sign, including a word (i.e. more than one character), or even a bunch
of text, with embedded whitespace?

Details are important...

int('X=   45   A'.split()[1])  will work on your example string, as will
int('X=   45   A'[5:7]) but neither is a very good way to go...

-Peter




More information about the Python-list mailing list