Extracting int from string

John Hunter jdhunter at ace.bsd.uchicago.edu
Mon Jan 13 23:44:52 CET 2003


>>>>> "Spencer" == Spencer Ernest Doidge <spencer at efn.org> writes:

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

With no error checking, etc, the following should speed you on your
way

  s = 'X=   45   A'
  x = int(s.split()[1])
  print x, type(x)

If your strings are more irregular than your example, eg, if

  s = 'X =   45   A'

is a legal string, you may want to look at module re's split.

John Hunter







More information about the Python-list mailing list