Python Implement String-to-Integer Conversion (Similar to int())
In Python, we can implement string-to-integer conversion with a custom function, similar to the built-in int() function. This function processes the digit characters in the string, ignores leading spaces and signs (+ or -), and then converts those characters into an integer.
Example
def
str_to_int
(
s
)
:
s
=
s.
strip
(
)
Remove leading and trailing spaces
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
Testing
(
str_to_int
(
" 123"
)
)
123
(
str_to_int
(
" -456"
)
)
-456
(
str_to_int
(
" +789"
)
)
789
(
str_to_int
(
" 12a34"
)
)
12
Code analysis:
s.strip(): Remove the spaces at the beginning and end of the stringsthe leading and trailing spaces of .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 is present, 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 digit and accumulate it into the result.return sign * result: Return the signed integer result.
Output result:
123
-456
789
12
Python3 Examples