Python: How can I read in the characters from a line in a file and convert them to floats and strs, depending on if they are numbers or letters?

Posted by user1467577 on Stack Overflow See other posts from Stack Overflow or by user1467577
Published on 2012-06-19T21:09:15Z Indexed on 2012/06/19 21:16 UTC
Read the original article Hit count: 135

Filed under:
|

I have a file that looks like:

1 1 C C 1.9873 2.347 3.88776

1 2 C Si 4.887 9.009 1.21

I would like to read in the contents of the file, line-by-line. When I only had numbers on the lines I used:

          for line in readlines(file):
                  data = map(float, line.split)

But this only works when all the elements of line.split are numbers. How can I make it store the letters as strings and the numbers as floats?

© Stack Overflow or respective owner

Related posts about python

Related posts about input