Python implementation of string to integer conversion (similar to int() function)

Document 对象参考手册Python3 Examples

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

Code explanation:

  1. s.strip(): remove the string'ssleading and trailing whitespace.
  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 exists, 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 number and accumulate it into the result.
  9. return sign * result: return the signed integer result.

Output result:

123
-456
789
12

Document 对象参考手册Python3 Examples

Other extensions