Python 字符串转数字
ringa_lee
ringa_lee 2017-04-17 14:34:24
0
3
950

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_lee
ringa_lee

ringa_lee

reply all(3)
阿神
这样行吗

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

PHPzhong

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template