Extract Integer from String in Python

How to extract integer from string in Python?

A string can store a sequence of characters. These characters can be alphabets, numbers, special characters, and more.

We will discuss how to extract integer from string in Python.

Using the isdigit() function to extract integer from string in Python.

In Python, the isdigit() function is used to check whether all the characters in a given string are digits or not.

To extract integer from string in Python with this function, we will check each character in a string and store every digit in a new string. This new string now contains the integer from the string and can be type cast to an integer using the int() function.

For example,

Output:

287

In the above example,

  • We iterate over a string using the for loop.
  • We use the if statement and check whether each character is a digit or not using the isdigit() method.
  • If the character is a digit, it is added to an empty string initialized beforehand.
  • We convert this string to an integer using the int() function.

Iterating over a string can be tedious and take a lot of time while working with long iterables. A quick way to use the isdigit() function is by applying the list comprehension technique.

In list comprehension, we aim to create a list using for loop in a single line of code. We will create a list of all the characters of the string that return True with the isdigit() function.

Finally, we will merge the characters of the list to a single string using the join() function and convert this string to an integer using the int() method.

This logic is implemented below.

Output:

287

Using the filter() function to extract integer from string in Python

This method uses the functions from the previous approach. The filter() function in Python can be used to filter out elements from a sequence based on a given function.

We can use the isdigit() function to filter out the digits, and combine them with the join() function as done previously.

See the following code.

Output:

287

Using the re.search() function to extract integer from string in Python

Regular expressions are a common way to identify substrings and process them using small patterns. These regex patterns can identify parts from the string.

We use the re module in Python to work with regular expressions in Python. With the re.search() function, we can find the occurrences of parts of the string that match a given regex pattern.

We will create a regex pattern to extract integer from string in Python using this function.

See the code below.

In the above example, we create a regex pattern \d+ that matches all the integers from the string. The re.search() function returns a Match object so we use the group() function to extract the results from this object. The int() method typecasts the result to an integer.

The re.findall() function from this module is also useful when we encounter multiple occurrences of integers. It returns the matches in a list.

Conclusion

In this article, we discussed how to extract integer from string in Python. In the first two methods, we use the isdigit() function in different ways to extract integer from string in Python. We extract each digit individually and combine them. The quick methods with this function involved the use of list comprehension and the filter() function. We also discussed how to use regex to extract integer from string in Python. We used the re.search() function to find the integer based on the regex pattern.

That’s all about how to extract Integer from String in Python.


import_contacts

You may also like:

Related Posts

  • 18 May

    Print a Character n Times in Python

    Table of ContentsUsing the * operator to print a character n times in PythonUsing the for loop to print a character n times in PythonConclusion In Python, the print() function is used to display some results on the output console. The print() function has evolved in Python. It started as a statement and it wasn’t […]

  • 18 May

    Get Variable from Function in Python

    Table of ContentsGet Variable from Function in PythonUsing the return statement to get variable from function in PythonUsing attributes to get variable from function in PythonConclusion Get Variable from Function in Python A function is a reusable piece of code that can be called at different places in a program. A function can execute some […]

  • 17 May

    Add Month to datetime in Python

    Table of ContentsWays to add month to datetime in PythonUsing the datetime.datetime constructor to add month to datetime in Python.Using the dateutil.relativedelta object to add month to datetime in PythonUsing the pandas.DateOffset() function to add month to datetime in PythonUsing the arrow.shift() function to add month to datetime in PythonConclusion In Python, we can represent […]

  • Convert CSV to dictionary in Python
    09 May

    Convert CSV to Dictionary in Python

    Table of ContentsCSV and Dictionaries in PythonConvert CSV to Dictionary in PythonUsing the pandas.to_dict() function to convert CSV to dictionary in PythonUsing the csv module to convert CSV to dictionary in PythonUsing the filter() function to convert CSV to dictionary in PythonUsing the numpy.loadtxt() function to convert CSV to dictionary in PythonConvert CSV to List […]

  • Make requirements.txt in Python
    03 May

    Make requirements.txt in python

    Table of ContentsWhat is the requirements.txt file in Python?Ways to make requirements.txt file in PythonUsing the pip to make requirements.txt in PythonUsing the conda command to make requirements.txt file in PythonUsing the pipreqs package to make requirements.txt file in PythonConclusion What is the requirements.txt file in Python? Every package is also updated regularly and features […]

  • Create an array of 1 to 10 in Python
    03 May

    Create an Array of 1 to 10 in Python

    Table of ContentsIntroductionHow to create an array of 1 to 10 in Python?Using the range() function to create an array of 1 to 10 in Python.Using list comprehension along with the range() function to create an array of 1 to 10 in Python.Using a user-defined function to create an array of 1 to 10 in […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.