[Tutor] Recognizing real numbers

Dave Angel d at davea.name
Wed Feb 22 23:52:37 CET 2012

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.

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?



More information about the Tutor mailing list