Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Implement String-to-Integer Conversion (Similar to int())

Python Implement String-to-Integer Conversion (Similar to int())

Document Object Reference Manual Python3 Examples

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

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 analysis:

  1. s.strip(): Remove the spaces at the beginning and end of the string s the leading and trailing spaces of .
  2. if not s:: If the string is empty, return 0.
  3. sign = 1: Initialize the sign to 1 (positive).
  4. if s[0] == '-' or s[0] == '+':: Check whether the first character of the string is a sign (+ or -).
  5. s = s[1:]: If a sign is present, remove the sign character.
  6. for char in s:: Iterate over each character in the string.
  7. if not char.isdigit():: If the character is not a digit, stop the conversion.
  8. result = result * 10 + (ord(char) - ord('0')): Convert the character to a digit and accumulate it into the result.
  9. return sign * result: Return the signed integer result.

Output result:

123
-456
789
12

Document Object Reference Manual Python3 Examples