473,796 Members | 2,618 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3408
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.99 9")) 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.99 9")) 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,3 2,"'%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.99 9"))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.99 9"))

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
9567
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 encrypt text before writing to a database and decrypt it when reading it back. I figured I'd use a MemoryStream that I can either store as a blob or convert to a string and store as a varchar. Anyway, I can't get the CryptoStream to write to the...
2
1577
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 reference C program I created. The input is a sequence of 32-bit integers, a 128 bit key (supplied as four 32-bit integers) and the number of passes. A separate function takes care of converting strings to these integers - four characters per 32-bit...
1
2402
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 - I need to change them to strings so that I can store the string "unknown" if these are not known. Problem is that my comparisons >= etc then won't work properly. Because of the way I am using the db I cannot have a pointer value, eg
3
278
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
3469
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
1386
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 or doubles, and I don't know what they will be ( I don't know how the parameter list will look like) . At the moment I have a mechanism that select all the values and read them into C++ strings, regardless of their type.
7
5049
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 involved. The problem is that comparisons between signed and unsigned values are machine- dependent, because they depend on the sizes of the various integer types. For example, suppose that int is 16 bits
409
11179
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 objects that are more than 4GB long. The problem is, when you have in thousands of places
1
9592
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 things (stored procedures, functions).. we have to manually edit. That time, we face some interesting challenges.. I failed to document all of them, but whatever I can share with u.. I will try.. :) ...
0
9685
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10459
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10237
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10018
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9055
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7553
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6795
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3735
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.