杰瑞科技汇

Python字符串转整数atoi如何实现?

Of course! The term "atoi" comes from the C/C++ library function atoi(), which stands for ASCII to Integer. Its purpose is to convert a string representation of a number into an actual integer.

Python字符串转整数atoi如何实现?-图1
(图片来源网络,侵删)

In Python, the built-in function that does this is int().

Here’s a complete guide covering the simple use case, the classic "atoi" problem (like on LeetCode), and other important related conversions.


The Simple Pythonic Way: int()

For most everyday use cases, you can simply use the int() constructor.

Basic Conversion

It works as long as the string contains only an optional sign ( or ) followed by digits.

Python字符串转整数atoi如何实现?-图2
(图片来源网络,侵删)
# Positive number
str_num = "123"
num = int(str_num)
print(f"Type: {type(num)}, Value: {num}")
# Output: Type: <class 'int'>, Value: 123
# Negative number
str_num = "-456"
num = int(str_num)
print(f"Type: {type(num)}, Value: {num}")
# Output: Type: <class 'int'>, Value: -456
# With a plus sign
str_num = "+789"
num = int(str_num)
print(f"Type: {type(num)}, Value: {num}")
# Output: Type: <class 'int'>, Value: 789

Handling Errors

If the string contains any non-digit characters (except for the leading sign), int() will raise a ValueError.

# This will cause an error
invalid_str = "12a34"
try:
    num = int(invalid_str)
except ValueError as e:
    print(f"Error: {e}")
# Output: Error: invalid literal for int() with base 10: '12a34'
# This will also cause an error
invalid_str = "  123" # Leading space
try:
    num = int(invalid_str)
except ValueError as e:
    print(f"Error: {e}")
# Output: Error: invalid literal for int() with base 10: '  123'

The "Classic Atoi" Problem (LeetCode #8)

This is a very common interview question. It's a more robust version of atoi that requires you to handle several edge cases explicitly.

Problem Statement

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.

The algorithm for myAtoi(string s) is as follows:

Python字符串转整数atoi如何实现?-图3
(图片来源网络,侵删)
  1. Read in and ignore any leading whitespace.
  2. Check if the next character (if not at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
  3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
  4. Convert these digits into an integer (e.g., "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0.
  5. Clamp the integer to the 32-bit signed integer range [-2^31, 2^31 - 1]. If the integer is out of the range [-2^31, 2^31 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -2^31 should be clamped to -2^31, and integers greater than 2^31 - 1 should be clamped to 2^31 - 1.
  6. Return the integer as the final result.

Python Implementation

Here is a Python function that solves this problem step-by-step.

def myAtoi(s: str) -> int:
    # 1. Read and ignore leading whitespace
    i = 0
    n = len(s)
    while i < n and s[i] == ' ':
        i += 1
    # If the string is empty after removing whitespace, return 0
    if i == n:
        return 0
    # 2. Determine the sign
    sign = 1
    if s[i] == '-':
        sign = -1
        i += 1
    elif s[i] == '+':
        i += 1
    # 3. Read in digits until a non-digit is found
    result = 0
    INT_MAX = 2**31 - 1
    INT_MIN = -2**31
    while i < n and s[i].isdigit():
        digit = int(s[i])
        # 5. Clamp the integer to the 32-bit signed integer range
        # Check for overflow *before* it happens
        if result > (INT_MAX - digit) // 10:
            return INT_MAX if sign == 1 else INT_MIN
        result = result * 10 + digit
        i += 1
    # 4. Apply the sign and return the result
    return sign * result
# --- Examples ---
print(f"'42' -> {myAtoi('42')}")              # Output: 42
print(f"'   -42' -> {myAtoi('   -42')}")      # Output: -42
print(f"'4193 with words' -> {myAtoi('4193 with words')}") # Output: 4193
print(f"'words and 987' -> {myAtoi('words and 987')}")   # Output: 0 (no digits at start)
print(f"'-91283472332' -> {myAtoi('-91283472332')}")     # Output: -2147483648 (clamped to INT_MIN)
print(f"'2147483648' -> {myAtoi('2147483648')}")       # Output: 2147483647 (clamped to INT_MAX)

Other Useful String-to-Number Conversions

While int() is for integers, Python has other functions for different numeric types.

float() - For Floating-Point Numbers

Converts a string to a floating-point number (a number with a decimal point).

str_float = "123.456"
num_float = float(str_float)
print(f"Type: {type(num_float)}, Value: {num_float}")
# Output: Type: <class 'float'>, Value: 123.456
# It can also handle scientific notation
str_sci = "1.23e4"
num_sci = float(str_sci)
print(f"Type: {type(num_sci)}, Value: {num_sci}")
# Output: Type: <class 'float'>, Value: 12300.0

eval() - Powerful but Dangerous

eval() can evaluate a string as a Python expression. This means it can handle numbers, but also much more.

WARNING: eval() is a massive security risk if the string comes from an untrusted source (like user input). It will execute any code, not just convert numbers.

# Safe usage with a trusted string
num_from_eval = eval("123")
print(f"Type: {type(num_from_eval)}, Value: {num_from_eval}")
# Output: Type: <class 'int'>, Value: 123
num_from_eval_float = eval("123.45")
print(f"Type: {type(num_from_eval_float)}, Value: {num_from_eval_float}")
# Output: Type: <class 'float'>, Value: 123.45
# DANGEROUS usage with untrusted input
# user_input = "__import__('os').system('echo pwned')" # This would delete your files!
# eval(user_input) # NEVER DO THIS

Summary: Which one should I use?

Function Use Case Example Handles Whitespace? Handles Signs? Handles Non-Digit Characters?
int() Simple, trusted integer conversion. int("123") No Yes No (raises ValueError)
myAtoi() Robust conversion with specific rules (e.g., interview questions). myAtoi(" -42") Yes Yes Yes (ignores after digits)
float() Convert string to a floating-point number. float("123.45") No Yes No (raises ValueError)
eval() Evaluate a string as a Python expression. eval("123 + 1") Yes Yes Yes (executes code)

Recommendation:

  • For standard, safe, and simple conversion, always use int() or float().
  • If you need to implement the specific "atoi" logic for an interview or a special application, use the myAtoi() implementation provided above.
  • Avoid eval() for converting numbers unless you are 100% certain the input string is safe and you need its full power.
分享:
扫描分享到社交APP
上一篇
下一篇