Python: how can I read characters from a string in a file and convert them to float and strs, depending on whether they are numbers or letters?

I have a file that looks like this:

1 1 CC 1.9873 2.347 3.88776 1 2 C Si 4.887 9.009 1.21 

I would like to read the contents of the file in turn. When I only had line numbers that I used:

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

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

+4
source share
3 answers
 for line in infile: data = [x if x.isalpha() else float(x) for x in line.split()] 

There will be problems if your data contains fields that are neither alphabetic nor valid floating point numbers (for example, "A1"). Your data does not seem to have what you said, but if so, Igor’s proposed try/except approach is probably better.

I would probably use a more general function that can be provided to the types that you need to try:

 def tryconvert(value, *types): for t in types: try: return t(value) except (ValueError, TypeError): continue return value for line in infile: data = [tryconvert(x, int, float) for x in line.split()] 

This will convert everything that will be converted to an integer into int , otherwise it will try a float , and then finally it just resets and returns the original value, which, as we know, will be a string. (If we did not know that it was a string, we could just insert str at the end of our call to tryconvert() .)

+1
source
 $ cat 1.py def float_or_str(x): try: return float(x) except ValueError: return x line = '1 1 CC 1.9873 2.347 3.88776' print map(float_or_str, line.split()) $python 1.py [1.0, 1.0, 'C', 'C', 1.9873, 2.347, 3.88776] 
+9
source

You can use the methods str.isalpha (), str.isalphanum (), str.isdigit to determine if your string is a number or not.

-1
source

All Articles