今天爱分享给大家带来python字符串转为float/int【面试题详解】,希望能够帮助到大家。
>>> a = "545.2222" >>> float(a) 545.2222 >>> int(a) Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: '545.2222' >>> int(float(a)) 545 >>> int('544') 544
另一种,用 ast模块
>>> import ast >>> ast.literal_eval("545.2222") 545.2222 >>> ast.literal_eval("31") 31