Jesse Rando
Jesse Rando

Reputation: 1

How to convert str in a list to int without using int() in Python

The question is pretty straightforward. Sorry I am very new to this. I'm not allowed to use int().

Upvotes: 0

Views: 231

Answers (4)

pzp
pzp

Reputation: 6597

Here is a nice, Pythonic way of doing it.

def str_to_int(s):
    if type(s) != str:
        raise TypeError("invalid type for str_to_int: {}".format(type(s)))
    if not s.isdigit():
        raise ValueError("invalid literal for str_to_int: '{}'".format(s))
    return sum((ord(char) - 48) * 10**(len(s) - n) for n, char in enumerate(s, start=1))

If you don't care about checking the argument to make sure it's a string and contains only digits, then it can be reduced down to the following one-liner:

str_to_int = lambda s: sum((ord(char) - 48) * 10**(len(s) - n) for n, char in enumerate(s, start=1))

Upvotes: 1

Ben
Ben

Reputation: 6348

This answer depends on the numbers' ASCII values being in sequential order. You want to simply reverse the string, then turn each digit to an int and add it's weighted value to the string. So, if your number is "12345", your first addend would be 5*1, or 5. Your second would be 4*10 or 40. Keep adding them and multiplying your weight by 10 until you reach the end of the string, and you are done!

def str_to_int(string):
    if not string.isdigit():
        raise ValueError("String must be a digit")
    weight = 1
    ans = 0
    for c in reversed(string):
        i = ord(c) - ord('0')
        ans = ans + i*weight
        weight = weight * 10
    return ans

If you can do it for one string, you can do it for all strings! Either use a for loop or the handy map function:

l = ["12312" , '32355']
print(list(map(str_to_int, l)))
print([str_to_int(i) for i in l])

Upvotes: 0

thebjorn
thebjorn

Reputation: 27311

Here is how to do it for binary (base2) numbers:

>>> bin(12)
'0b1100'
>>> sum([2**i * (ord(ch)-ord('0')) for i, ch in enumerate(reversed('1100'))])
12

Upvotes: 1

Dominique McDonnell
Dominique McDonnell

Reputation: 2520

The algorithm you are looking for is:

initialise number to 0
for each character in str
    multiply number by 10
    find number of character (ascii value, avaiable from ord(), - 48 is simplest) 
    add character number to number

Of course, you should check that the string is actually all numbers first.

Upvotes: 1

Related Questions