How to Convert a String to an Integer in Python With Examples and Error Handling

 

 Why Convert String to Integer?

In Python, user input and data from files or APIs are often in string format (str). To perform arithmetic or numeric operations, you must convert them to integers (int).

 Basic Conversion Using int()

 Syntax:

int("123")

 Example:

num_str = "42"
num_int = int(num_str)
print(num_int + 10)  # Output: 52

 What If the String Is Not a Number?

 Error Example:

int("hello")  # ValueError: invalid literal for int()

 How to Handle Conversion Errors

 Use try-except to Handle ValueError:

user_input = "abc"

try:
    number = int(user_input)
    print("Converted number:", number)
except ValueError:
    print("Invalid input. Please enter a numeric string.")

 Strip Whitespace Before Conversion

num_str = "  55  "
num_int = int(num_str.strip())
print(num_int)  # Output: 55

 What About Float Strings?

int("3.14")  #  ValueError

 Convert to float first, then to int if needed:

num = int(float("3.14"))  # Output: 3

 Summary Table

Input Type Method Output
"123" int("123") 123 (int)
" 42 " int(" 42 ".strip()) 42 (int)
"3.14" int(float("3.14")) 3 (int)
"abc"  Raises ValueError Handle with try

Best Practices

  • Always validate input before conversion.
  • Use str.isdigit() to check if a string is numeric:
    if "123".isdigit():
        print("Safe to convert")

0 Comments:

Post a Comment