Convert String to int in Python

Boost Your Career with In-demand Skills - Start Now!

As a Python programmer, you may come across situations where you need to convert a string into an integer. This process may seem simple, but it is crucial to get it right. In this blog, we will discuss how to convert a Python string to an integer. We will also cover different methods for doing so and highlight their benefits and drawbacks.

Convert String to int

In Python, converting a string to an integer is a common task. A string can contain numerical characters, and we can convert it to an integer using built-in functions.

To convert a string to an integer, we use the int() function. This function takes a string as input and returns an integer value. However, there are a few things to keep in mind when using the int() function.

Below are some bullet points that summarize the topics that we will cover in this blog:

  • The basic syntax of the int() function
  • Converting a string with numerical characters to an integer
  • Converting a string with non-numerical characters to an integer
  • Converting a string to an integer with a default value
  • Using the try-except block for error handling while converting a string to an integer
  • Real-time examples of converting a string to an integer

Basic Syntax of the int() Function:

The syntax of the int() function is straightforward. The int() function takes a string as input and returns an integer.

Here is the basic syntax of the int() function:

int(string, base=10)
  • string: The string that needs to be converted to an integer.
  • base: This parameter is optional and represents the number system to which the string belongs. The default value is 10.

Converting a String with Numerical Characters to an Integer:

When the string contains numerical characters, the int() function converts the string to an integer without any issues.

Let’s see an example below:

str_number = "1234"
int_number = int(str_number)
print(int_number)

Output:
1234

Converting a String with Non-numerical Characters to an Integer:

If the string contains non-numerical characters, the int() function throws a ValueError. Let’s see an example below:

str_number = "12a4"
int_number = int(str_number)
print(int_number)

Output:
ValueError: invalid literal for int() with base 10: ’12a4′

Converting a String to an Integer with a Default Value:

If the string contains non-numerical characters, we can assign a default value to the int() function. This default value is returned instead of a ValueError. Let’s see an example below:

str_number = "12a4"
int_number = int(str_number, 0)
print(int_number)

Output:
0

Using the Try-Except Block for Error Handling While Converting a String to an Integer:

To handle errors while converting a string to an integer, we can use the try-except block. The try block contains the code that can raise an exception. The except block catches the exception and handles it. Let’s see an example below:

str_number = "12a4"
try:
    int_number = int(str_number)
    print(int_number)
except ValueError:
    print("Oops!  That was no valid number.  Try again...")

Output:
Oops! That was no valid number. Try again…

Real-time Examples of Converting a String to an Integer:

1. Converting User Input:

Whenever we need a user to input a number, we will get the input as a string. In such cases, we can convert the input string to an integer using the int() function.

age = int(input("Enter your age: "))

In the above example, we are getting the age of the user as input, which will be in string format. So, we convert it to an integer using the int() function.

2. String to Integer Conversion for Calculation:

If we want to perform arithmetic operations on the string, we first need to convert it to an integer using the int() function. Here is an example:

num1 = "10"
num2 = "5"
result = int(num1) + int(num2)
print(result)

In the above example, we are adding two numbers, num1 and num2. Since num1 and num2 are in string format, we need to convert them to integers using the int() function before performing the addition.

3. Converting String to Integer to Check Whether a String is Numeric:

We can also convert a string to an integer to check whether it is numeric or not. Here is an example:

num = "10"
if num.isnumeric():
    print("The string is numeric")
else:
    print("The string is not numeric")

In the above example, we are checking whether the string num is numeric or not. We convert the string to an integer using the int() function to check whether it is numeric or not.

Conclusion

Converting a string to an integer is a common operation in Python, and it can be done easily using the int() function. In this article, we learned what the int() function is and how it works. We also discussed some real-time examples where converting a string to an integer comes in handy. By following the guidelines and examples mentioned in this article, you can easily convert a string to an integer in Python.

If you are Happy with PythonGeeks, do not forget to make us happy with your positive feedback on Google | Facebook


PythonGeeks Team

The PythonGeeks Team offers industry-relevant Python programming tutorials, from web development to AI, ML and Data Science. With a focus on simplicity, we help learners of all backgrounds build their coding skills.

1 Response

  1. Petr says:

    The example:

    str_number = “12a4”
    int_number = int(str_number, 0)
    print(int_number)

    does not work and is wrong. the second parameter is base, not a default value

Leave a Reply

Your email address will not be published. Required fields are marked *