Python implementation of string to integer conversion (similar to int() function)
In Python, we can implement string-to-integer conversion through a custom function, similar to the built-inint()function. This function processes the numeric characters in the string, ignores leading spaces and signs (+ or -), and converts these characters into an integer.
Example
def str_to_int(s):
s = s.strip() # Remove leading and trailing whitespace
if not s:
return 0
sign = 1
if s[0] == '-' or s[0] == '+':
if s[0] == '-':
sign = -1
s = s[1:] # Remove the sign
result = 0
for char in s:
if not char.isdigit():
break
result = result * 10 + (ord(char) - ord('0'))
return sign * result
# Test
print(str_to_int(" 123")) # 123
print(str_to_int(" -456")) # -456
print(str_to_int(" +789")) # 789
print(str_to_int(" 12a34")) # 12
s = s.strip() # Remove leading and trailing whitespace
if not s:
return 0
sign = 1
if s[0] == '-' or s[0] == '+':
if s[0] == '-':
sign = -1
s = s[1:] # Remove the sign
result = 0
for char in s:
if not char.isdigit():
break
result = result * 10 + (ord(char) - ord('0'))
return sign * result
# Test
print(str_to_int(" 123")) # 123
print(str_to_int(" -456")) # -456
print(str_to_int(" +789")) # 789
print(str_to_int(" 12a34")) # 12
Code explanation:
s.strip(): remove the string'ssleading and trailing whitespace.if not s:: if the string is empty, return 0.sign = 1: initialize the sign to 1 (positive).if s[0] == '-' or s[0] == '+':: check whether the first character of the string is a sign (+ or -).s = s[1:]: if a sign exists, remove the sign character.for char in s:: iterate over each character in the string.if not char.isdigit():: if the character is not a digit, stop the conversion.result = result * 10 + (ord(char) - ord('0')): convert the character to a number and accumulate it into the result.return sign * result: return the signed integer result.
Output result:
123 -456 789 12Other extensions
Python3 Examples