杰瑞科技汇

Python字符串如何转为整数?

Of course! Converting a string to an integer is a fundamental operation in Python. Here’s a complete guide covering the primary method, common errors, and more advanced scenarios.

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

The Main Method: int()

The primary and most common way to convert a string to an integer is by using the built-in int() function.

Basic Syntax

int_string = "123"
integer_value = int(int_string)
print(integer_value)
print(type(integer_value))

Output:

123
<class 'int'>

Handling Different Number Bases (Radix)

The int() function has an optional second argument, radix, which specifies the base of the number in the string. The default is 10 (for decimal numbers).

Base radix value Example String Conversion
Binary 2 "1010" int("1010", 2)10
Octal 8 "12" int("12", 8)10
Decimal 10 "10" int("10", 10)10
Hexadecimal 16 "A" int("A", 16)10

Code Examples:

Python字符串如何转为整数?-图2
(图片来源网络,侵删)
# Binary to Decimal
binary_str = "1010"
decimal_from_binary = int(binary_str, 2)
print(f"'{binary_str}' in binary is {decimal_from_binary} in decimal.")
# Output: '1010' in binary is 10 in decimal.
# Octal to Decimal
octal_str = "12"
decimal_from_octal = int(octal_str, 8)
print(f"'{octal_str}' in octal is {decimal_from_octal} in decimal.")
# Output: '12' in octal is 10 in decimal.
# Hexadecimal to Decimal
hex_str = "FF"
decimal_from_hex = int(hex_str, 16)
print(f"'{hex_str}' in hex is {decimal_from_hex} in decimal.")
# Output: 'FF' in hex is 255 in decimal.

Note: When using a base other than 10, the string must not have a prefix like 0b (for binary), 0o (for octal), or 0x (for hex). The int() function will raise a ValueError if it encounters these prefixes when a radix is provided.

# This will cause an error
try:
    int("0b1010", 2)
except ValueError as e:
    print(f"Error: {e}")
# Output: Error: invalid literal for int() with base 2: '0b1010'

Common Errors and How to Handle Them

ValueError: When the string is not a valid number

This is the most common error. It occurs if the string contains non-numeric characters, whitespace, or is empty.

invalid_str = "123abc"
try:
    num = int(invalid_str)
except ValueError:
    print(f"Cannot convert '{invalid_str}' to an integer.")
# Output: Cannot convert '123abc' to an integer.

Solution: You must clean the string first.

# Example: Remove currency symbols and commas
price_str = "$1,234.50"
# First, remove non-digit characters except for the negative sign
cleaned_str = "".join(char for char in price_str if char.isdigit() or char == '-')
# Then, convert to integer
try:
    price_int = int(cleaned_str)
    print(price_int)
except ValueError:
    print("Could not convert the cleaned string to an integer.")
# Output: 123450

TypeError: When the input is not a string

The int() function expects a string (or another number type). If you pass a different type, like a list or None, you'll get a TypeError.

Python字符串如何转为整数?-图3
(图片来源网络,侵删)
not_a_string = [1, 2, 3]
try:
    num = int(not_a_string)
except TypeError as e:
    print(f"Error: {e}")
# Output: Error: int() argument must be a string, a bytes-like object or a real number, not 'list'

Advanced Scenarios

Converting a String with a Decimal Part (e.g., "3.14")

If you try to convert a string representing a float directly to an int, you will get a ValueError.

float_str = "3.14"
try:
    num = int(float_str)
except ValueError as e:
    print(f"Error: {e}")
# Output: Error: invalid literal for int() with base 10: '3.14'

Solution 1: Convert to float first, then to int This is the most common and robust solution. The int() function will then perform truncation, meaning it will cut off the decimal part.

float_str = "3.14"
float_num = float(float_str)  # Step 1: Convert to float
int_num = int(float_num)      # Step 2: Convert to int (truncates .14)
print(int_num) # Output: 3
# For negative numbers, it truncates towards zero
neg_float_str = "-3.99"
neg_int_num = int(float(neg_float_str))
print(neg_int_num) # Output: -3

Solution 2: Use round() for Rounding If you want to round to the nearest integer instead of truncating, use the round() function.

float_str = "3.9"
rounded_num = round(float(float_str))
print(rounded_num) # Output: 4

Converting a String with Commas

Strings representing large numbers often use commas as thousand separators. The int() function cannot parse these directly.

number_with_commas = "1,000,000"
try:
    num = int(number_with_commas)
except ValueError as e:
    print(f"Error: {e}")
# Output: Error: invalid literal for int() with base 10: '1,000,000'

Solution: Remove the commas before converting.

number_with_commas = "1,000,000"
# The replace() method is perfect for this
cleaned_str = number_with_commas.replace(',', '')
num = int(cleaned_str)
print(num) # Output: 1000000

Summary Table

Your Goal Method Example
Basic Conversion int(string) int("42")42
Convert from Binary int(string, 2) int("1010", 2)10
Convert from Hex int(string, 16) int("FF", 16)255
Handle Decimal String int(float(string)) int(float("3.9"))3
Handle Commas int(string.replace(',', '')) int("1,000".replace(',', ''))1000
Handle Errors Use a try...except ValueError block See examples above
分享:
扫描分享到社交APP
上一篇
下一篇