2015-08-25 11 views
4

假設我們知道所有的字符串都是某個數字的某種表示形式。 foo函數返回我們傳入的字符串的數值。我也想檢查一個數字的傳遞的字符串表示是整數還是浮點數。 但是我不確定這是否是最優雅的方式。有更簡單/更清潔的方法嗎?將十分之零和百分之一的浮動字符串轉換爲python中的整數2.7

def foo(arg): 
     if arg.endswith('.00'): 
      arg3 = arg3[:-3] 
     try: 
      arg3 = int(arg3) 
     except: 
      arg3 = float(arg3) 

     return arg 


    arg1 = '3456.26' 
    arg2 = '100.00' 

    num1 = foo(arg1) 
    num2 = foo(arg2) 

回答

3

浮點數有is_integer method,它告訴你他們是否是等於整與否:

>>> (1.23).is_integer() 
False 
>>> (1.0).is_integer() 
True 

因此你可以使用它來寫類似:

def to_number(s): 
    """Converts a string to a number.""" 
    f = float(s) 
    return int(f) if f.is_integer() else f 

(請注意,我避免使用"bare except"。在使用中:

>>> for x in ('1.23', '123', '1.00', 'foo'): 
    print x, to_number(x) 


1.23 1.23 
123 123 
1.00 1 
foo 

Traceback (most recent call last): 
    File "<pyshell#11>", line 2, in <module> 
    print x, to_number(x) 
    File "<pyshell#8>", line 5, in to_number 
    f = float(s) 
ValueError: could not convert string to float: foo 
+0

你可以簡化刪除try ... except部分 – bilbo

+0

@bilbo當然你是對的;那是我誤解了這個問題的早期版本的宿醉! – jonrsharpe

相關問題