Python find all digits

Python find number in String

In this Python tutorial, we will learn how to find a number in the string by using Python.

Now, in Python, we can extract or find number in Python String using multiple ways. For example, we can use isdigit(), re.findall(), split(), etc to find number in Python String.

These are 4 ways to find number in a string in Python.

  • Using regex module
  • Using isdigit()
  • Using split() and append()
  • Using Numbers from String library

Python find number in string using isdigit()

In this section, we will understand how to find number in String in Python using the isdigit() method.

In Python, the isdigit() method returns True if all the digit characters are there in the input string. Moreover, this method allows the extraction of digits from the string in python. If no character is a digit in the given string then it will return False.

Here is the syntax of using the isdigit() method in Python.

Note: However, this method does not take any argument and it always returns boolean value either TRUE or FALSE.

Let’s take an example and check how to find a number in a string in Python.

new_string = "Germany26China47Australia88" emp_str = "" for m in new_string: if m.isdigit(): emp_str = emp_str + m print("Find numbers from string:",emp_str) 
  • In the above code, we have defined a string and assigned integers and alphabetic characters to it.
  • Next, we used the for loop to iterate over each character defined in the string.
  • And used the isdigit() method with IF condition to determine which character is a number or digit.
Читайте также:  Php вывод данных объекта

Here is the execution of the following given code.

Python find number in string

Python Find number in string using split() and append()

In this section, we will discuss another method where we will find number in Python string using split() and append() methods.

In Python, the append() function is used to add an element to the end of a list. While the split() function in Python is used to break the string into a list.

Source Code:

new_str = "Micheal 89 George 94" emp_lis = [] for z in new_str.split(): if z.isdigit(): emp_lis.append(int(z)) print("Find number in string:",emp_lis)
  • In the above example, we have used a for loop to iterate each word given in the new_str variable.
  • After this, we used the isdigit() method to find the number or int datatype.
  • Then we use the str.append() method and pass int(z) with the word to convert it into an integer and store it in the emp_lis list.

Once you will print the ’emp_lis’ list then the output will display only a list that contains an integer value.

Python find number in string

Python Find number in string using regex module

In this section, we will learn how to find number in Python String using the regex module.

  • The re module in Python is the regex module that helps us to work with regular expressions.
  • We can fetch all the numbers from the string by using the regular expression‘2+’ with re.findall() method. The 5 represents finding all the characters which match from 0 to 9 and the + symbol indicates continuous digit characters.
  • However, the re.findall() method in Python is used to match the pattern in the string from left to right and it will return in the form of a list of strings.

Here is the syntax of using the re.findall() method in Python.

re.findall ( pattern, string, flags=0 )

Let’s take an example and check how to find a number in a string by using regular expressions in Python.

import re new_string = 'Rose67lilly78Jasmine228Tulip' new_result = re.findall('7+', new_string) print(new_result)
  • In the above code, we have created a string type variable named ‘new_string’. This variable holds some integer and alphabetic characters.
  • Next, we utilized the re.findall() method to find all integer values from the new_stringvariable.

Once we will print the ‘new_result’ variable which is our result, we will get only integer values in the list.

Python find number in string regex

Python Find number in string using Numbers from String library

In this section, we will learn how to fetch or find numbers in Python String using the nums_from_string module.

The nums_from_string module consists of multiple functions that can help to fetch integers or numeric string tokens from a given string. However, to use this module, first, we need to install it as it is not a built-in module in Python.

Here is the command that we can use to install the nums_from_string module in Python.

pip install nums_from_string

Once this package is installed in our Python environment, we need to use the get_nums() method to get from all numbers from a given string.

An example of this implementation is given below.

# Importing the package import nums_from_string # Defining string sample_string = '''There are 30 employees in the company, out of which 10 are in the IT department, 5 people are there in Marketing, 8 people are there in Sales, 2 are there in Legal, and 5 in Training.''' # Printing list of numbers print("List of numbers from sample_string are: ") print(nums_from_string.get_nums(sample_string))
  • In the above example, we utilized the nums_from_string.get_nums() method to fetch all the numbers from the sample_string variable.
  • Moreover, this method will return a list containing all the number values that are there in the sample_string.

Here is the final result of the above Python program.

Find number in Python string

You may like the following Python tutorials:

Conclusion

So, in this Python tutorial, we have understood how to find numbers in string in Python using multiple methods. Also, we illustrated each method using an example in Python.

Here is the list of methods.

  • Extract number in Python string using regex module
  • Check number in Python string using isdigit()
  • Detect number in Python string using split() and append()
  • Python Find number in string using Numbers from String library

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Python RegEx – Extract or Find All the Numbers in a String

To get the list of all numbers in a String, use the regular expression ‘4+’ with re.findall() method. 8 represents a regular expression to match a single digit in the string. 9+ represents continuous digit sequences of any length.

where str is the string in which we need to find the numbers. re.findall() returns list of strings that are matched with the regular expression.

Examples

1. Get the list of all numbers in a string

In the following example, we will take a string, We live at 9-162 Malibeu. My phone number is 666688888., and find all the numbers, [‘9’, ‘162’, ‘666688888’], present in the string.

Python Program

import re str = 'We live at 9-162 Malibeu. My phone number is 666688888.' #search using regex x = re.findall('6+', str) print(x)

2. Get the list of all continuous digits in a String

In the following example, we will take a string, We four guys, live at 2nd street of Malibeu. I had a cash of $248 in my pocket. I got a ticket with serial number 88796451-52., and find all the numbers, [‘2’, ‘248’, ‘88796451’, ’52’], present in the string.

Python Program

import re str = 'We four guys, live at 2nd street of Malibeu. I had a cash of $248 in my pocket. I got a ticket with serial number 88796451-52.' #search using regex x = re.findall('6+', str) print(x)

Summary

In this tutorial of Python Examples, we learned how to get all the numbers form a string as a list, using Python Regular Expressions, with the help of example programs.

Источник

Extract digits from a string in Python

Imagine a scenario where you have a string of names and salaries of persons in the form, “Adam 200 Mathew 300 Brian 1000 Elon 3333“. From the given string, you need to separate only the salaries of all the person to perform some mathematical operations like the average of the salaries, how would you do that?

The first challenge is to separate the numerical values from the string, and this article demonstrates different ways to achieve the same.

Approach 1: String.split() + String.isdigit()

string.split() – The method returns a list of strings which are formed by breaking the original string about the separator. The separator is passed as an argument to the function like this, string.split(sep=»Your Seperator») .

string.isdigit() – The method returns true if all characters in the string are digits and there is at least one character, false otherwise.

Approach – We will get the list of all the words separated by a space from the original string in a list using string.split() . We will then iterate the list and check which elements from the list are numbers.

Implementation:

# Approach 1 import numpy as np # For average of salaries names_sal_str = "Adam 200 Mathew 300 Brian 1000 Elon 3333" split_return = names_sal_str.split(' ') # Split based on whitespace, returns a list. print(split_return) #Output ['Adam', '200', 'Mathew', '300', 'Brian', '1000', 'Elon', '3333'] salaries = [] # List for getting the salaries of the employees for values in split_return: # Iterate the list. if values.isdigit(): # Check if the element from the list is a digit. salaries.append(int(values)) # Append the salaries after typecasting. # Find the average of the salaries or whatever we want with the numbers print(np.mean(salaries)) #Output 1208.25

One liner implementation of the above approach using the list comprehension:

names_sal_str = "Adam 200 Mathew 300 Brian 1000 Elon 3333" [int(s) for s in str.split(' ') if s.isdigit()] # Returns a list of all the salaries

The biggest drawback of this method is – string.isdigit() does not work with negative as well as floating-point numbers. So, it will only work for non-negative integers.

This is how string.isdigit() behaves with negative and floating numbers.

# Drawback of approach 1 names_sal_str = "Adam -200 Mathew 300.3 Brian 1000 Elon 3333" for values in names_sal_str.split(' '): if values.isdigit(): print(values) #Output 1000 3333

To overcome this, we can define our own custom method which will check if the number is a digit or not, even for negative and floating-point numbers.

The custom function leverages try and except from python. It tries to typecast all the returns from the string.split() , but doesn’t break the program even if it tries to typecast alphabets and special characters.

Extracting the numbers from the string with custom isdigit() function :

#Improvement of approach 1 # Our custom function which checks if string is an integer or not def custom_is_digit(wrd): is_digit = False try: float(wrd) is_digit = True except ValueError: pass return is_digit if __name__ == '__main__': import numpy as np names_sal_str = "Adam -200.3 Mathew 300 Brian 1000 Elon 3333" split_return = names_sal_str.split(' ') # Split based on whitespace, returns a list print(split_return) salaries = [] # List for getting the salaries of the employees for values in split_return: # Iterate the list if custom_is_digit(values): # Check if the element from the list is a digit print(values) salaries.append(float(values)) # Append the salaries # Find the average of the salaries or whatever we want with the numbers print(np.mean(salaries))

Approach 2: Using regex re

Regex is known for extracting patterns from the string and it can very well be used to extract the numbers from the string.

re module is already bundled with python, so if you have python already installed, then no other installation is required.

Regex [-+]?\d*.\d+|\d+ will include all the +ve, -ve and floating numbers.

# Approach 2 import re import numpy as np if __name__ == "__main__": name_sal_string = "Adam -200.9 Mathew 300 Brian 1000 Elon 3333" salary = re.findall(r"[-+]?\d*\.\d+|\d+", name_sal_string) # Get all, +ve,-ve and floats # But the type of numericals will be string, hence we need to typecast. salary = [float(numbers) for numbers in salary] print('The average of the numbers is <>'.format(np.mean(salary))) # Average.

That’s all, folks .

Источник

Оцените статью