[Tutor] Recognizing real numbers

Michael Lewis mjolewis at gmail.com
Thu Feb 23 02:54:54 CET 2012


On Wed, Feb 22, 2012 at 2:52 PM, Dave Angel <d at davea.name> wrote:

> On 02/21/2012 10:00 PM, Michael Lewis wrote:
>
>> Hi everyone,
>>
>> I have some code where I import a file to use a module. That module that I
>> import takes text and a multiplier, checks for any numbers in that text
>> and
>> will then multiply those numbers by the given multiplier. The imported
>> module is below. I am getting the text from a file that I have which
>> starts
>> out as:
>>
>> .5 lb. butter
>> 1.75 Cups Graham Cracker Crumbs
>> 2.0 Cups Powder Sugar
>> 1.0 Cups Peanut Butter
>> 2.0 Cups Semi-sweet Chocolate Chips
>>
>> It seems that the .isdigit() function that I use doesn't recognize the .5
>> as a number and therefore doesn't multiply it. How can I get my code to
>> recognize numbers such as .5, 1.75 as numbers?
>>
>> Imported module:
>>
>> def MultiplyText(text, multiplier):
>>     '''Recieve a S&  int. For digits in S, multiply by multiplier and
>>
>> return updated S.'''
>>     return ' '.join(str(float(num) * multiplier) if num.isdigit() else num
>> for num in text)
>>
>>  Somehow, every other time I read that code I missed the "for num in
> text" phrase that was wrapped around by the mail.
>

No worries - this list has been crazy helpful to me.

>
> I'm apologizing for my earlier remarks stating that this function would
> not work.  i would clean up the variable names (text is a list, and num is
> a string), and the function comment states that you're multiplying
> individual digits).  But since it works, it's a good base to start with for
> your floating point question.
>
> Easiest answer is to write a function that does check if a string is a
> valid float, the same as num.isdigit()  (lousy names also occur in the
> standard library) does for int.
>
> The new function would be easiest to write with a try/except form.  Take a
> string as a formal parameter, try to float() it in a try block, and if it
> succeeds, return True.
>
> It'd be convenient if there were such a method in str, but since there
> isn't, you'd have to change  num.isdigit() to  isfloat(num).
>
> Have you gotten to try/except in your class yet?


We have. I actually have a function written in my imported file to check if
a string is a valid float, but I didn't use it because I also have
raw_input in that same function, which I don't want. I'll rework the
imported function to remove the raw_input and put that in a function by
itself so I can utilize the valid float try/except that I've already
written.

>
>
> --
>
> DaveA
>
>


-- 
Michael J. Lewis

mjolewis at gmail.com
415.815.7257
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120222/9591b44d/attachment.html>


More information about the Tutor mailing list