Convert string to int in Python

Key takeaways:

  • Use Python’s built-in int() function to easily convert numeric strings to integers, e.g., int("123").

  • The int() function can convert strings representing numbers in various bases, such as binary (int("1010", 2)) or hexadecimal (int("1F", 16)).

Converting a string to an integer is a common task in Python programming. Whether we’re processing user input, parsing data, or working on computations, knowing how to handle this operation efficiently is crucial.

A string is given to the int() function
A string is given to the int() function
1 of 3

Using the int() function

The most straightforward way to convert a string to an integer is by using Python’s built-in int() function.

Note: The function returns 0 if no arguments are passed.

Syntax

int(x, base=10)
Syntax parameters for int()
Syntax parameters for int()

The int() function takes a string (or any object) representing a number and converts it into an integer. The function performs the conversion without errors if the string contains valid numeric characters.

Here’s a breakdown of the parameters it takes:

  • x: The value to convert into an integer. It can be:

    • A number (e.g., float, bool)

    • A string representing an integer (e.g., "42")

    • A string representing a number in a different base (e.g., "1010" in binary)

  • base: The base of the number system for conversion.

    • If x is a string, base specifies the number system (e.g., 2 for binary, 16 for hexadecimal, 8 for octal).

    • If x is a number (not a string), base is ignored.

print(int("42")) # Output: 42

Converting strings with different bases in Python

Python provides built-in functions to convert strings representing numbers in different bases (binary, octal, hexadecimal) into integers and vice versa.

# Converting a binary string to an integer
binary_str = "1010" # Binary representation of 10
binary_num = int(binary_str, 2)
print("Binary to Integer:", binary_num)
# Converting an octal string to an integer
octal_str = "12" # Octal representation of 10
octal_num = int(octal_str, 8)
print("Octal to Integer:", octal_num)
# Converting a hexadecimal string to an integer
hex_str = "A" # Hex representation of 10
hex_num = int(hex_str, 16)
print("Hexadecimal to Integer:", hex_num)

Handling invalid input strings in Python

When converting strings to numbers, invalid inputs (such as non-numeric characters) can cause errors. We can handle such cases using try-except and isdigit() method.

1. Handling invalid input using try-except

The try block attempts to convert the string to an integer. If the string contains invalid characters (like letters or decimals), a ValueError is raised and caught in the except block. An error message is printed, and None is returned.

def safe_convert_to_int(s):
"""Converts a string to an integer safely using try-except."""
try:
return int(s) # Attempt conversion
except ValueError:
print(f"Error: '{s}' is not a valid integer.")
return None
# Test cases
inputs = ["123", "42a", "98.6", "-50", "ten"]
for input_str in inputs:
result = safe_convert_to_int(input_str)
print(f"Input: '{input_str}' → Output: {result}")

Learn the basics with our engaging Learn Python course!

Start your coding journey with Learn Python, the perfect course for beginners! Whether exploring coding as a hobby or building a foundation for a tech career, this course is your gateway to mastering Python—the most beginner-friendly and in-demand programming language. With simple explanations, interactive exercises, and real-world examples, you’ll confidently write your first programs and understand Python essentials. Our step-by-step approach ensures you grasp core concepts while having fun. Join now and start your Python journey today—no prior experience is required!

2. Handling invalid input using str.isdigit()

isdigit() checks if the string consists only of digits (0-9). It does not support negative numbers ("-50" will fail). If isdigit() returns True, the string is converted to an integer. If False, an error message is printed, and None is returned.

def safe_convert_with_isdigit(s):
"""Converts a numeric string to an integer using isdigit()."""
if s.isdigit():
return int(s)
else:
print(f"Error: '{s}' is not a purely numeric string.")
return None
# Test cases
inputs = ["123", "42a", "98.6", "-50", "ten"]
for input_str in inputs:
result = safe_convert_with_isdigit(input_str)
print(f"Input: '{input_str}' → Output: {result}")

Conclusion

The int () function in Python makes converting a string to an integer simple and versatile. We can easily handle various scenarios by incorporating techniques such as error handling, stripping whitespace, and validating input.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What does int() do in Python?

The int() function in Python converts a value to an integer.


How do you convert an int to a string in Python f-string?

An f-string (formatted string literal) is a way to embed expressions inside string literals using curly braces {}. It is prefixed with f or F and allows for easier and more readable string formatting.

You can convert an integer to a string within an f-string by simply placing the integer variable within curly braces {}.

my_int = 42
my_string = f"The answer is: {my_int}" 
print(my_string)  # Output: The answer is: 42

What is toString() in Python?

Python does not have a built-in method called toString(). We can implement toString() to convert a value to a string in Python.


Can we convert string to int in Python?

Yes, you can convert a string to an integer in Python using int():

integer_num = int("100")  # Output: 100

What happens if the string contains non-numeric characters?

The int() function will raise a ValueError if the string contains non-numeric characters (except for leading/trailing spaces, a sign, or a valid base prefix).

Example:

int("123abc")  # Raises ValueError

Can int() handle strings with leading or trailing spaces?

Yes, int() automatically ignores leading and trailing spaces before conversion.

Example:

print(int("  42  "))  # Output: 42

Is there a way to check if a string can be converted to an integer before using int()?

Yes, use str.isdigit() or a try-except block.

Example:

s = "123"
if s.isdigit():
    print(int(s))  # Output: 123

Or using try-except:

try:
    num = int(s)
    print(num)
except ValueError:
    print("Cannot convert to int")

Can I convert a floating-point string to an integer?

Yes, but you must first convert it to a float and then to an integer (which removes the decimal part).

Example:

print(int(float("12.34")))  # Output: 12

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved