search

Home  >  Q&A  >  body text

Python 字符串转数字

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))
ringa_leeringa_lee2788 days ago956

reply all(3)I'll reply

  • 阿神

    阿神2017-04-17 14:36:24

    这样行吗
    
    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)
    

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 14:36:24

    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)))
    

    For

    Thanks, but '234jdsf23232ks' will be converted to 23423232, which is not the desired result

    In this case, I looked at the original question again. In fact, the key point of the original question is to peel off such a simple problem "Find the position of the first character that is not a number in the string ".

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

    After finding this location, then use the slicing function and int method to complete the task.

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

    The idea is similar to the question ^-^

    reply
    0
  • PHPz

    PHPz2017-04-17 14:36:24

    Borrowing from itertools treasure, the core code is in one sentence
    takewhile Returns the iterator of the elements that meet the conditions at the head.

    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

    reply
    0
  • Cancelreply