You are currently viewing Python Convert String to Int (Integer)

By using the int() function you can convert the string to int (integer) in Python. Besides int() there are other methods to convert. Converting a string to an integer is a common task in Python that is often necessary when working with user input, reading data from a file, or interacting with a database. There are several ways to do this, and it is important to understand the different methods and the potential use of each method.

Advertisements

1. Quick Examples of Converting String to Int

These quick examples include different approaches to give you a high-level overview of how to convert string to int. We will discuss this more in detail.


# Quick examples of converting string to int

# Using the int() function
strObj = "123"
result = int(strObj)

# Using the float() function 
strObj = "123.45"
float_num = float(strObj)
result = int(float_num)

# Using the bit_length() 
strObj = "10010101"
result = int(strObj, 2)

# Using the PyNumber_Long()
import sys
strObj = "1234567890"
result = int(sys.intern(strObj))

2. Python Convert String to Int using int()

To convert string to int (integer) type use the int() function. This function takes the first argument as a type String and second argument base. You can pass in the string as the first argument, and specify the base of the number if it is not in base 10. The int() function can also handle negative integers by recognizing the negative sign in the string.


# Convert str to int
strObj = "987"
result = int(strObj)
print("Converting string to integer:",result)

Yields below output.

Python convert string to int

To convert a string that represents a negative integer to an actual integer in Python, you can use the int() function as usual. For instance, the string “-654” is converted to the integer -654. The int() function can handle negative numbers represented as strings just like positive numbers.


# Convert str with negative to int
strObj = "-654"
result = int(strObj)
print("Converting negative string to integer:",result)

Yields below output.

Python convert string to int

If the string is not the valid integer value in the specified base, it will raise a ValueError. You can use a try-except block to handle this error and ensure that your code runs smoothly. The int() function is not able to convert a floating point number represented as a string into an integer.


# Convert string with non-int
try:
    strObj = "123.45"
    result = int(strObj)
except ValueError:
    print("String is not an integer.")

# Output: 
# String is not an integer.

3. Using Base Parameter of int()

You can use the base parameter to specify a base between 2 and 36, inclusive. For example, you can use the base parameter to convert a string that represents a base 8 (octal) number to an integer


# Use Base 2 (binary) while convertion
strObj = "10010101"
result = int(strObj, 2)
print(result)  

# Output: 
# 149

# Base 8 (octal) while convertion
strObj = "765"
result = int(strObj, 8)
print(result) 
 
# Output: 
# 501

# Base 36 (alphanumeric)
strObj = "zzzzz"
result = int(strObj, 36)
print(result) 
 
# Output: 
# 60466175

4. Convert String to Int By Checking Is Digit

In the above examples, we saw that we will see a valueError if something bad happens. You can use the isdigit() method in combination with the int() function to safely convert a string to an integer without encountering a ValueError exception.


# Check if the str is a digit before convertion
def str_to_int(strObj: str) -> int:
    if strObj.isdigit():
        return int(strObj)
    else:
        return 0

strObj = "89"
result = str_to_int(strObj)
print(result)  

# Output: 
# 89

strObj = "xyz"
result = str_to_int(strObj)
print(result)
  
# Output: 
# 0

5. Converting String with Float to Int

Sometimes you may be required to convert the string with a float value to int (integer) in Python. The float() function can be used to convert a string to a float and pass the result to int() to convert the floating-point number to an integer. As a result, the int() function will remove any trailing decimals from the string.

Here is an example of using the float() & int() functions to convert a string to an integer:


# Convert str with float to int
strObj = "12.56"
result = int(float(strObj))
print(result) 
 
# Output: 
# 12

strObj = "23.000"
result = int(float(strObj))
print(result)
  
# Output: 
# 23

6. Handling Invalid Input

When the int() function is used to convert a string to an integer, it will raise a ValueError if the string is not a valid integer. This can happen if the string is empty, contains non-numeric characters, or has a leading or trailing whitespace.

You might have seen this in other examples as well. To handle this error, you can use a try and except statement as shown below.


# Handling invalid input example
# With Valid Integer
strObj = "53"  
try:
    result = int(strObj)
except ValueError:
    result = 0
print(result)  

# Output: 
# 53

# With invalid integer
strObj = "abc"  
try:
    result = int(strObj)
except ValueError:
    result = 0
print(result)  

# Output: 
# 0

7. Good Practices to Convert String to Integer in Python

The following methods of strings can be used to make sure that the string is ready to convert to an int in Python. These include removing leading and trailing whitespace using the strip() method of string. It also includes removing any non-numeric characters using the replace() method of string and extracting the numeric portion of the string using regular expressions.

7.1 Eliminating Whitespaces using strip()

This technique can be particularly useful if the string you are trying to convert contains leading or trailing whitespaces, which can cause the int() function to raise a ValueError exception when it is passed an invalid argument.

Below is an example of how you can use the strip() method to remove leading and trailing whitespaces from a string before attempting to convert it to an integer.


# Strip whitespaces
strObj = "   67 "
stripped_string = strObj.strip()
result = int(stripped_string)
print(result)  

# Output: 
# 67

7.2 Removing non-numeric Characters using replace

To remove non-numeric characters from a string, you can use the replace() method, which is a built-in method of the str class in Python. The replace() method will remove the characters specified in the old string argument.


# Remove non-numeric characters
strObj = "345xyz"
cleaned_string = strObj.replace("x", "").replace("y", "").replace("z", "")
result = int(cleaned_string)
print(result)  

# Output: 
# 345

To make it more generalized, we can use the string module in python. Here is an example that shows you how to do that.

  • Create a string of all alphabetical characters using string.ascii_lowercase and string.ascii_uppercase.
  • Use translate() with maketrans() to remove all alphabetical characters from string.
  • Convert cleaned_string to an integer with int().

import string

strObj = "abc345xyz"
alphabet = strObj.ascii_lowercase + strObj.ascii_uppercase
cleaned_string = strObj.translate(strObj.maketrans("", "", alphabet))
result = int(cleaned_string)
print(result)  

# Output: 
# 345

7.3 Extract Numeric Portion of String with regex

The re module includes a variety of functions and methods that can be used to search, replace, and split strings using regular expressions. To extract the numeric portion of a string using regular expressions, you can use the re module, which is a built-in module in Python that provides support for regular expressions.


#Extract numeric portion of string
import re

strObj = "123abc456"
match = re.search(r"\d+", strObj)
if match:
    result = int(match.group())
    print(result)  
else:
    print("Invalid input")

# Output: 
# 123456

Frequently Asked Questions on Python Convert String to Integer

How do I convert a string to an integer in Python?

To convert a string to an integer in Python, you can use the int() function. For example, the int() function is used to convert the string "123” to the integer 123. If the string contains non-numeric characters or is in an invalid format, a ValueError will be raised. Always ensure that the string represents a valid integer before attempting the conversion.

Can I convert a string with a negative number to an integer?

You can convert a string with a negative number to an integer in Python. The int() function can handle negative numbers represented as strings.

What happens if the string contains non-numeric characters?

If the string contains non-numeric characters or is in an invalid format, a ValueError will be raised. Always ensure that the string represents a valid integer before attempting the conversion.

How do I handle floating-point numbers represented as strings?

If the string represents a floating-point number, you can use the float() function to convert it to a floating-point number first and then use int() to truncate the decimal part if needed.

Is there a way to handle errors during conversion?

You can handle errors during conversion by using a try-except block. When you attempt to convert a string to an integer using the int() function, a ValueError will be raised if the string is not a valid integer representation.

Summary and Conclusion

In this article, we learned various techniques of how to convert string to int (integer) in Python. These methods can be useful for handling different types of input and requirements in your code. If you have any further questions about converting strings to integers in Python, don’t hesitate to ask.