不使用int()将String转换为Int

Eug*_*e K 6 python python-3.x

我试图实现add2strings,sub2strings,mult2strings在Python功能.如果你这样做的话int(string),它们都很容易,但是我想在没有它的情况下完成它们,而不会导入另外的欺骗性事情Decimal.我目前的想法是使用bytes.

还有另一种方法吗?

daw*_*awg 10

参考atoiC中的基础知识:

int myAtoi(char *str)
{
    int res = 0; // Initialize result

    // Iterate through all characters of input string and update result
    for (int i = 0; str[i] != '\0'; ++i)
        res = res*10 + str[i] - '0';

    // return result.
    return res;
}
Run Code Online (Sandbox Code Playgroud)

这转化为Python:

def atoi(s):
    rtr=0
    for c in s:
        rtr=rtr*10 + ord(c) - ord('0')

    return rtr
Run Code Online (Sandbox Code Playgroud)

测试一下:

>>> atoi('123456789')
123456789   
Run Code Online (Sandbox Code Playgroud)

如果您希望以下列方式容纳可选符号和空格int:

def atoi(s):
    rtr, sign=0, 1
    s=s.strip()
    if s[0] in '+-':
        sc, s=s[0], s[1:]
        if sc=='-':
            sign=-1

    for c in s:
        rtr=rtr*10 + ord(c) - ord('0')

    return sign*rtr
Run Code Online (Sandbox Code Playgroud)

现在添加例外,你就在那里!