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
则不会出现类似问题
javascript
var num = parseInt('2323d') num == 2323
那么,如何用python实现一个类似js的parseInt
函数(尽量不用正则)
下面是我实现的一个,但是有没有更好的方法
python
def 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))
For
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 ".
After finding this location, then use the slicing function and int method to complete the task.
The idea is similar to the question ^-^
Borrowing from
itertools
treasure, the core code is in one sentencetakewhile
Returns the iterator of the elements that meet the conditions at the head.