Convert String to Int and Arithmetic

kyosohma at gmail.com kyosohma at gmail.com
Tue Jun 12 16:46:07 CEST 2007


On Jun 12, 9:32 am, tereglow <tereg... at yahoo.com> wrote:
> Hello,
>
> I am a complete newbie to Python and am accustomed to coding in PHP/
> Perl/Shell.  I am trying to do the following:
>
> I have a string:
>
> cpuSpeed = 'Speed: 1000000000'
>
> What I would like to do is extract the '1000000000' from the string,
> and divide that by 1000 twice to get the speed of a processor in MHz.
>
> My understanding is that I need to 'import re' and then use re.split
> to get the first part done.  The second part confuses me because I'm
> unable to convert the '1000000000' to an integer to run division
> against it.
>
> Basically, I want to come out with 1000 for the above string.  Any
> help would be appreciated.
> Tom

You don't need to use the "re" module. I'd just do something like
this:

>>> temp = cpuSpeed.split(' ')
>>> temp
['Speed:', '1000000000']
# grab the 2nd element from the list and cast it as an integer
>>> cpuSpeed = int(temp [1])
>>> cpuSpeed = (cpuSpeed / 1000) / 1000
>>> cpuSpeed
1000

Basically, you just use the split command and cast it as an integer
using the reserved word "int".

Then you can divide it twice.

Mike




More information about the Python-list mailing list