# [Tutor] string to int or float

Gregor Lingl glingl at aon.at
Mon Nov 3 10:09:31 EST 2003

Jimmy verma schrieb:

>
> Yes that worked for me. Thanks a lot for your suggestions.
>
> Really this list is of great help as it is having helpful persons around.

May I, just for fun, supplay another funny solution to your problem:

>>> def str2num(s):
return "." in s and float(s) or int(s)

>>> map(str2num, ['207','-308','-8.0','6','.5'])
[207, -308, -8.0, 6, 0.5]

This one uses the so called "short-circuit-evaluation"  (am I right?) of
logical operations. That means, that operands of logical expressions
are evaluated only  if necessary and then the value of the last evaluated
operand is returned. In the case  above:

If "." is s is True, then float(s) is (successfully) evaluated and retured,
otherwise the second operand of the or, i. e. int(s) has to be evaluated
(as the first one is False) and the result of this evaluation is returned.

Alas! I remember that zeros count as False in Python, so

>>> str2num('0.')

Traceback (most recent call last):
File "<pyshell#18>", line 1, in -toplevel-
str2num('0.')
File "<pyshell#17>", line 2, in str2num
return "." in s and float(s) or int(s)
ValueError: invalid literal for int(): 0.
>>>
The conjunction remains false and the second part ot the or doesn't work.
So there must not be a floatingpoint zero in your list. Except...

... hmm, there was somewhere, somewhen, somehow a wokaround (I'd bet
this came from a German mailing list), ah...,  I remember:

>>> def str2num(s):
return ("." in s and [float(s)] or [int(s)])[0]

>>> map(str2num, ['207','-308','-8.0','6','.5', '0.0'])
[207, -308, -8.0, 6, 0.5, 0.0]
>>>

(A list that contains a zero is True! So we construct one
and use its first element.  8-) )

Regards,
Gregor

More information about the Tutor mailing list