Question

In a text file I have to write values, and next to each value either "NUMERIC" if the value's type is int or float, or "NOMINAL", if the type is str. I know that this could be solved by an if statement, but I would be pleased to use a more elegant way. I thought of multiplication with a boolean - something like that:

outputfile.write(value1 + "_NOMINAL" * (type(value1) is str)
                        + "_NUMERIC" * (type(value1) is (float or int)))

This does not work - I don't know why... It works if I change the second expression into two conditions:

+ "_NUMERIC" * ((type(value1) is float) or (type(value1) is int))

Is there any other elegant, pythonic approach to get this done?

Was it helpful?

Solution

If you really think this is elegant (a matter of taste, I guess), try:

outputfile.write(value1 + "_NOMINAL" * (type(value1) is str)
                        + "_NUMERIC" * (type(value1) in (float, int)))

If you ask me, I think I'd write it like this (assuming the value would only be a string or a number):

print >> outputfile, value1, "NOMINAL" if type(value1) is str else "NUMERIC"

or, if you want to allow for values that are elements of subclasses of str:

print >> outputfile, value1, "NOMINAL" if isinstance(value1, str) else "NUMERIC"

If there were more things changing, depending on the type of the value, or if there were more than two types, I'd use an if.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top