为了账号安全,请及时绑定邮箱和手机立即绑定

Python 字符串转数字

Python 字符串转数字

holdtom 2019-02-24 19:28:33
python自带的int函数在值中出现字符串的情况下会出现错误 python>>> int('232d') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '232d' 而js中parseInt则不会出现类似问题 javascriptvar num = parseInt('2323d') num == 2323 那么,如何用python实现一个类似js的parseInt函数(尽量不用正则) 下面是我实现的一个,但是有没有更好的方法 pythondef safe_int(num): try: return int(num) except ValueError: result = [] for c in num: if not ('0' <= c <= '9'): break result.append(c) if len(result) == 0: return 0 return int(''.join(result))
查看完整描述

4 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

这样行吗

def safe_int(num):
    assert isinstance(num, basestring)
    try:
        return int(num)
    except ValueError:
        result = "0"
        for c in num:
            if c not in string.digits:
                break
            result += c
        return int(result)
查看完整回答
反对 回复 2019-03-01
?
眼眸繁星

TA贡献1873条经验 获得超9个赞

python    from functools import reduce
    def parseInt(s):
        return reduce(lambda x, y: x*10+y, map(int, filter(lambda c : c>='0' and c<='9', s)))

针对

谢谢,但是'234jdsf23232ks'会转换为23423232,这不是想要的结果

这一情况,再看了下原问题,其实原问题关键之处即在于剥离出这样一个简单问题“查找到字符串中第一个不为数字的字符的位置”。

python    def find(s):
        for i in range(len(s)):
            if not '0'<=s[i]<='9':
                return i
        return len(s)

找到这个位置后,然后用切片函数和int方法就可以完成任务了。

python    s = '234jdsf23232ks'
    idx = find(s)
    int(s[0:idx])

思路跟题主的差不多^-^

查看完整回答
反对 回复 2019-03-01
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

借用itertools宝藏的话,核心代码一句话
takewhile 返回头部符合条件的元素的迭代器。

from itertools import takewhile
def parseInt(s):
    assert isinstance(s, basestring)
    return int(''.join(list(takewhile(lambda x:x.isdigit(),s)))) if s[0].isdigit() else None
查看完整回答
反对 回复 2019-03-01
?
FFIVE

TA贡献1797条经验 获得超6个赞

借用 C 语言的 atoi 思路给你写了一个:

#!/usr/bin/python

def parseInt(s):
    res = 0 
    base = ord('0')
    for c in s:
        if not ('0' <= c <= '9'):
            break
        res *= 10
        res += ord(c) - base
    return res 

var1 = '1234abc';
print parseInt(var1)
查看完整回答
反对 回复 2019-03-01
  • 4 回答
  • 0 关注
  • 488 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信