Extracting int from string

Skip Montanaro skip at pobox.com
Mon Jan 13 17:24:42 EST 2003


    Spencer> What would be the best way to extract the integer value 45 from
    Spencer> the following string?

    Spencer> 'X=   45   A'

Depends entirely on how regular your data is.  If your integer is guaranteed
to always be the second of three "words", each separated by white space,
something like

    s = 'X=   45   A'
    number = s.split([1])

will suffice.  If there might not be any white space after the equal
sign (as people are wont to do), then perhaps a regular expression will do
the trick:

    s = 'X=45   A'
    import re
    mat = re.search(r'[^=]+=\s*([0-9]+)', s)
    if mat is not None:
    number = mat.group(1)

Skip





More information about the Python-list mailing list