Solution Review: String to Integer
This lesson contains the solution review to convert a string into an integer in Python.
We'll cover the following...
We'll cover the following...
In this lesson, we will review the solution to the challenge in the last lesson. The problem is as follows:
Given some numeric string as input, convert the string to an integer.
You already know that we are not allowed to use the built-in int()
function. Now to convert a string into an integer, we can make use of the following arithmetic:
As you can see, by multiplying each digit with the appropriate base power, we can get the original integer back. Let’s implement this in Python.
Implementation
Press + to interact
Python 3.5
def str_to_int(input_str):output_int = 0if input_str[0] == '-':start_idx = 1is_negative = Trueelse:start_idx = 0is_negative = Falsefor i in range(start_idx, len(input_str)):place = 10**(len(input_str) - (i+1))digit = ord(input_str[i]) - ord('0')output_int += place * digitif is_negative:return -1 * output_intelse:return output_ints = "554"x = str_to_int(s)print(type(x))s = "123"print(str_to_int(s))s = "-123"print(str_to_int(s))
Explanation
On line 3, output_int
is initialized to 0
. The code on lines 5-10 ...