473,397 Members | 1,985 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,397 software developers and data experts.

String/Number Conversion

Hello Folks!

I've got a little problem here, which which really creeps me out at the
moment.
I've got some strings, which only contain numbers plus eventually one
character as si-postfix (k for kilo, m for mega, g for giga). I'm trying
to convert those strings to integers, with this function:
def eliminate_postfix(value):
if type(value) is str:
value.upper()
if value.endswith('K'):
mult = 1000
elif value.endswith('M'):
mult = 1000000
elif value.endswith('G'):
mult = 1000000000
else:
mult = 1

if mult is 1:
value = string.atoi(value)
else:
value = string.atoi(value[:-1]) * mult
return value

The problem is as follows: Everytime a string with a postfix should get
converted, mult does not get set properly. It is always 1. Does anyone
have an idea how to fix this? I just don't see it, maybe because I'm
pretty new to python or because I'm just blind I would be really greatful.

Kind regards,
Andy
Sep 6 '08 #1
7 2385
On Sep 6, 5:04*pm, Andreas Hofmann <asdfasdfasdfasdfa...@arcor.de>
wrote:
Hello Folks!

I've got a little problem here, which which really creeps me out at the
moment.
I've got some strings, which only contain numbers plus eventually one
character as si-postfix (k for kilo, m for mega, g for giga). I'm trying
to convert those strings to integers, with this function:

def eliminate_postfix(value):
* * * * *if type(value) is str:
* * * * * * * * *value.upper()
* * * * * * * * *if value.endswith('K'):
* * * * * * * * * * * * *mult = 1000
* * * * * * * * *elif value.endswith('M'):
* * * * * * * * * * * * *mult = 1000000
* * * * * * * * *elif value.endswith('G'):
* * * * * * * * * * * * *mult = 1000000000
* * * * * * * * *else:
* * * * * * * * * * * * *mult = 1

* * * * * * * * *if mult is 1:
* * * * * * * * * * * * *value = string.atoi(value)
* * * * * * * * *else:
* * * * * * * * * * * * *value = string.atoi(value[:-1]) * mult
* * * * *return value

The problem is as follows: Everytime a string with a postfix should get
converted, mult does not get set properly. It is always 1. Does anyone
have an idea how to fix this? I just don't see it, maybe because I'm
pretty new to python or because I'm just blind I would be really greatful..

Kind regards,
Andy
Hello,

1. You call value.upper(), but you do not capture the results of that
method. Strings are immutable in Python.
>value = value.upper()
2. You should use == instead of "is" in the comparison of mult being
1.
>if mult == 1:
Sep 6 '08 #2
On Sat, 06 Sep 2008 23:04:14 +0200, Andreas Hofmann wrote:

Hi,
I've got a little problem here, which which really creeps me out at the
moment.
I've got some strings, which only contain numbers plus eventually one
character as si-postfix (k for kilo, m for mega, g for giga). I'm trying
to convert those strings to integers, with this function:
if mult is 1:
^^
You're testing for identity, not for equality.
Change it to "if mult == 1". Is it alright now?
--
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
Sep 6 '08 #3
On Sep 7, 7:04 am, Andreas Hofmann <asdfasdfasdfasdfa...@arcor.de>
wrote:
Hello Folks!

I've got a little problem here, which which really creeps me out at the
moment.
I've got some strings, which only contain numbers plus eventually one
character as si-postfix (k for kilo, m for mega, g for giga). I'm trying
to convert those strings to integers, with this function:

def eliminate_postfix(value):
if type(value) is str:
Don't use "is" unless you are really sure that "==" won't do the job.
Better idiom:
if isinstance(value, str):
value.upper()
This causes your "mult is always 1" problem. You need:
value = value.upper()
Why? Because strings are immutable. String methods like upper return a
new string, they don't change the existing string.
if value.endswith('K'):
mult = 1000
elif value.endswith('M'):
mult = 1000000
elif value.endswith('G'):
mult = 1000000000
else:
mult = 1

if mult is 1:
Lose "is". In fact, lose the whole "if" statement. See below.
value = string.atoi(value)
Don't use deprecated functions from the string module. Use the built-
in float function to convert from text.
else:
value = string.atoi(value[:-1]) * mult
return value
Those last few statements look somewhat tortuous. Try this:
else: # mult would be 1, but we don't need it
return float(value)
return float(value[:-1]) * mult

HTH,
John
Sep 6 '08 #4
On Sep 7, 7:29*am, Wojtek Walczak <gmin...@bzt.bztwrote:
On Sat, 06 Sep 2008 23:04:14 +0200, Andreas Hofmann wrote:
* * * * * * * * *if mult is 1:

* * * * * * * * * * * * * *^^
You're testing for identity, not for equality.
Change it to "if mult == 1". Is it alright now?
Although he definitely should not be using "is" here, that can not be
the problem if he is using CPython. As an optimisation, small integers
are interned i.e. for each small integer, there is only one object.
>>a = 1
b = 10000
a is 1
True
>>b is 10000
False
>>id(a)
10897704
>>id(1)
10897704
>>id(b)
11893004
>>id(10000)
12633044
>>>
Sep 6 '08 #5
Andreas Hofmann, there are several problems in your code:
if type(value) is str:
Better to use isinstance() and to compare it with basestring instead.

value.upper()
This does nothing, python strings are immutable, so they don't get
changed in-place, so you have to assign that result to some name,
possibly a different name.
I also suggest you to strip the uppered string, to remove head/tail
spaces.
Your indenting isn't much good, I suggest you to use only four spaces
for each indent (you can also use one tab, but I don't suggest this).

if value.endswith('K'):
mult = 1000
elif value.endswith('M'):
mult = 1000000
elif value.endswith('G'):
mult = 1000000000
else:
mult = 1
This is okay. You can also put those key-values in a dict, that you
can access with the get method with a default 1, but it may be
overkill.

if mult is 1:
value = string.atoi(value)
else:
value = string.atoi(value[:-1]) * mult
return value
Instead of using string.atoi, use the int() builtin.

If you follow my suggestions you will have a function that works in
many situations. It will raise exceptions in other situations, but
that's good.

But to not need much of our help in your future code I suggest you to
use the Python shell and test every line you write. I also suggest you
to start right now using tests, for example like this:

def eliminate_postfix(value):
"""
>>el_post = eliminate_postfix
el_post(1)
1
>>el_post("100")
100
>>el_post("")
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: ''
>>el_post("100g")
100000000000L
>>el_post("100G ")
100000000000L
>>el_post("100 G ")
100000000000L
>>el_post("100hg")
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: '100H'
>>el_post(" 100 k ")
100000
>>el_post(" 100m")
100000000
>>el_post(u"100m")
100000000
"""
... function code ...
if __name__ == "__main__":
import doctest
doctest.testmod()
print "Doctests done.\n"

That will improve your coding a LOT, reducing your bug count, etc.

Bye,
bearophile
Sep 6 '08 #6
Thanks a lot, I got it working now.
Thanks also to the other guys, your numerous hints were really valuable!

Kind regards,
Andy

John Machin schrieb:
On Sep 7, 7:04 am, Andreas Hofmann <asdfasdfasdfasdfa...@arcor.de>
wrote:
>Hello Folks!

I've got a little problem here, which which really creeps me out at the
moment.
I've got some strings, which only contain numbers plus eventually one
character as si-postfix (k for kilo, m for mega, g for giga). I'm trying
to convert those strings to integers, with this function:

def eliminate_postfix(value):
if type(value) is str:

Don't use "is" unless you are really sure that "==" won't do the job.
Better idiom:
if isinstance(value, str):
> value.upper()

This causes your "mult is always 1" problem. You need:
value = value.upper()
Why? Because strings are immutable. String methods like upper return a
new string, they don't change the existing string.
> if value.endswith('K'):
mult = 1000
elif value.endswith('M'):
mult = 1000000
elif value.endswith('G'):
mult = 1000000000
else:
mult = 1

if mult is 1:

Lose "is". In fact, lose the whole "if" statement. See below.
> value = string.atoi(value)

Don't use deprecated functions from the string module. Use the built-
in float function to convert from text.
> else:
value = string.atoi(value[:-1]) * mult
return value

Those last few statements look somewhat tortuous. Try this:
else: # mult would be 1, but we don't need it
return float(value)
return float(value[:-1]) * mult

HTH,
John
Sep 6 '08 #7
Andreas Hofmann wrote:
I've got some strings, which only contain numbers plus eventually one
character as si-postfix (k for kilo, m for mega, g for giga). I'm trying
to convert those strings to integers, with this function:
Why bother to always switch the case if you only use a few values?
Also, the Python style is to do an operation and handle failures, rather
than test first.

Try something like:

_units = dict(K=1000, M=1000000, G=1000000000,
k=1000, m=1000000, g=1000000000)

def eliminate_postfix(value):
try:
return _units[value[-1]] * int(value[: -1])
except (TypeError, KeyError):
return int(value)

If you normally do not have the suffixes, then switch it around:

def eliminate_postfix(value):
try:
return int(value)
except ValueError:
return _units[value[-1]] * int(value[: -1])
If this is really SI units, you likely are doing real measurements,
so I'd consider using "float" instead of "int" in the above.
--Scott David Daniels
Sc***********@Acm.Org
Sep 6 '08 #8

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

Similar topics

4
by: ken | last post by:
I've been looking for a solution to a string to long conversion problem that I've run into >>> x = 'e10ea210' >>> print x e10ea210 >>> y=long(x) Traceback (most recent call last): File...
17
by: jake1138 | last post by:
Here is a function I have to get a number at the end of a string. I'm posting this in case it proves helpful to someone. Comments are welcome. int getnum(char *str) { char buffer; char *buf...
9
by: fooboo | last post by:
Does anyone know if a easier way (built in function, or something) that can verify that a string is an alphanumeric number? Here is what I am doing now: for(i=0; i < strlen(temp); i++){...
6
by: karthi | last post by:
hi, I need user defined function that converts string to float in c. since the library function atof and strtod occupies large space in my processor memory I can't use it in my code. regards,...
6
by: tommaso.gastaldi | last post by:
Hi, does anybody know a speedy analog of IsNumeric() to check for strings/chars. I would like to check if an Object can be treated as a string before using a Cstr(), clearly avoiding the time...
8
by: Salvatore Di Fazio | last post by:
Hi guys, how can I convert a hex string in a sequence of chars? I've thought, if I get a hex string like that: 54657374 I need to get number one for time and convert it in decimal in the...
1
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number?...
10
by: Hank Stalica | last post by:
I'm having this weird problem where my code does the following conversion from string to float: 27000000.0 -27000000.00 2973999.99 -29740000.00 2989999.13 -2989999.25 The number on the left...
2
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number?...
3
by: TamaThps | last post by:
I have an array of string values, and I need to access each character of the string individually. For instance I want my char variable to equal the first character in the string, and then compare it...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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
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
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,...
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.