Problems with conversion of values in strings to integers
Jørgen Cederberg
jorgencederberg at hotmail.com
Thu Oct 9 07:05:17 EDT 2003
Bengt Richter wrote:
> On Mon, 06 Oct 2003 14:06:26 +0200, Peter Otten <__peter__ at web.de> wrote:
>
>>Jørgen Cederberg wrote:
>>
>>> Hi,
>>>
>>> using Python 2.2.1 on Windows and QNX I'm having trouble understandig
>>> why int() raises a ValueError exception upon converting strings.
>>>
<snip example of converting strings/floats with int()>
>>>
>>> This is quite frustating. The only solution I can see is to do:
>>> >>> int(float('10.1'))
>>> 10
>>>
>>> Is this the only solution or are there any other way to do this?
>>
>>
<snip - atoi example>
>>
>>>>> int(float("1.999"))
>>1
>>
>>>>> int(round(float("1.999")))
>>2
>>
>>I think it's good that Python does not make the decision for you. Once you
>>have decided which route to go you can easily wrap it into a helper
>>function, e. g.
>>
>>def toInt(s):
>> try:
>> return int(s)
>> except ValueError:
>> return int(round(float(s)))
>>
>>(When dealing with user input, things are a little more complicated, as the
>>decimal separator changes between locales)
>>
> There's that too ;-)
Actually my problem arose using the Scale widget in Tkinter. The small
program below demonstrates the problem.
The first line with Scale doesn't work, as the IntVar(!), tries to
convert a string from Tkinter, that is in fact a float. This results
from the Tkinter function getint, which is the same as int.
--------------------------
from Tkinter import *
def onScale(value):
print "The value is", value,"and its type is", type(value)
print "The variable is", var.get(),"and its type is", type(var.get())
root = Tk()
var = IntVar()
# This does'nt work. The value inside the Scale is now a float
represented in
# string, which int() can't handle.
#s = Scale(root, length=100, bd=1, digit=3, from_ = -10,
#to=10,variable=var, command=onScale)
# This works.
s = Scale(root, length=100, bd=1, from_ = -10, to=10,variable=var,
command=onScale)
s.pack()
root.mainloop()
--------------------------
One might argue that it doesn't make sense to use the Scale with digits
together with an IntVar, but in my case to from_ and to values can both
be integers and floats.
Regards
Jorgen
More information about the Python-list
mailing list