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() .)
source share