473,405 Members | 2,185 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Problems with conversion of values in strings to integers

Hi,

using Python 2.2.1 on Windows and QNX I'm having trouble understandig
why int() raises a ValueError exception upon converting strings.
int('-10') -10 int('10') 10 int(10.1) 10 int('10.1') Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 10.1

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?

Regards
Jorgen Cederberg

Jul 18 '05 #1
5 3387
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.
>>> int('-10') -10 >>> int('10') 10 >>> int(10.1) 10 >>> int('10.1') Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 10.1

This is quite frustating. The only solution I can see is to do: >>> int(float('10.1')) 10


depending on what you actually want,
int(round('10.1'))

might be appropriate.
But if you really want the "floor"-value,
nothing is wrong with your approach.

Karl

Jul 18 '05 #2
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.
>>> int('-10') -10 >>> int('10') 10 >>> int(10.1) 10 >>> int('10.1') Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 10.1

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?

There is more than one way to convert a string representing a fp number to
an integer:
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)

Peter

Jul 18 '05 #3
Peter Otten 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 examples of converting strings 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?



There is more than one way to convert a string representing a fp numberto
an integer:
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, asthe
decimal separator changes between locales)


Thanks a lot for the function. It solves the problem elegantly.

/Jorgen

Jul 18 '05 #4
On Mon, 06 Oct 2003 14:06:26 +0200, Peter Otten <__*******@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.
>>> int('-10') -10
>>> int('10')

10
>>> int(10.1)

10
>>> int('10.1')

Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 10.1

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?

There is more than one way to convert a string representing a fp number to
an integer:

Indeed, but what if the OP wants something like C's atoi? E.g.,
(playing with MinGW and MSYS -- pretty neat, BTW ;-)

[14:35] /c/pywk/clp/atoi>cat pratoi.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
if(argc<2){
printf("Usage: pratoi strings ...\n");
} else {
int i;
char sbuf[32];
for(i=1;i<argc;++i){
snprintf(sbuf,32,"'%s'",argv[i]);
printf("%8s => %d\n", sbuf, atoi(argv[i]));
}
}
return 0;
}
[14:35] /c/pywk/clp/atoi>gcc pratoi.c -o pratoi
[14:35] /c/pywk/clp/atoi>pratoi 0 1 -1 +1 123 4.5 -5.6 -1.2e3 0x11 011 " -3xx" " -xx"
'0' => 0
'1' => 1
'-1' => -1
'+1' => 1
'123' => 123
'4.5' => 4
'-5.6' => -5
'-1.2e3' => -1
'0x11' => 0
'011' => 11
' -3xx' => -3
' -xx' => 0

Note the 'way different result on -1.2e3 in particular. Also does the OP want to ignor
octal and hex or reject them?

atoi looks like it just strips leading spaces, takes and optional sign, and computes
a decimal from as many decimal digits as it can then find (including none as ok).

I'll leave that as an exercise for python ;-)
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 ;-)

Regards,
Bengt Richter
Jul 18 '05 #5
Bengt Richter wrote:
On Mon, 06 Oct 2003 14:06:26 +0200, Peter Otten <__*******@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, asthe
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

Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Stingray | last post by:
Are there any know problems with using a MemoryStream as a backing store for a CryptoStream? I'm trying to simply encrypt and decrypt text in memory. I'd like to create some simple methods to...
2
by: Bryan Feeney | last post by:
My life was full and happy lately, which just wan't right, so I've ended up trying to implement an encryption algorithm through JavaScript! However the output I'm getting doesn't match the...
1
by: Monkey Steve | last post by:
Hi, I'm writing a website in asp.net(vb) with an access database behind it. As part of the site I have a table which has stores maximum and minimum values. These are integers at present. However...
3
by: Jack | last post by:
Simple question: Does anyone know how to convert integer values to character strings that can written to binary files? For example -1 = Hex(FFFF) etc..
90
by: John Salerno | last post by:
I'm a little confused. Why doesn't s evaluate to True in the first part, but it does in the second? Is the first statement something different? False print 'hi' hi Thanks.
3
by: d.avitabile | last post by:
I have a C++ code that is reading a list of parameters from a file. PARAMETERS stringParam="stringValue", intParam=4, doubleParam = 3.533, ... END The values can be strings as well as integers...
7
by: somenath | last post by:
Hi All, I am trying to undestand "Type Conversions" from K&R book.I am not able to understand the bellow mentioned text "Conversion rules are more complicated when unsigned operands are...
409
by: jacob navia | last post by:
I am trying to compile as much code in 64 bit mode as possible to test the 64 bit version of lcc-win. The problem appears now that size_t is now 64 bits. Fine. It has to be since there are...
1
ssnaik84
by: ssnaik84 | last post by:
Hi Guys, Last year I got a chance to work with R&D team, which was working on DB scripts conversion.. Though there is migration tool available, it converts only tables and constraints.. Rest of...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.