Extract numbers from string list Python

PythonServer Side ProgrammingProgramming

While using python for data manipulation, we may come across lists whose elements are a mix of letters and numbers with a fixed pattern. In this article we will see how to separate the numbers form letters which can be used for future calculations.

With split

The split functions splits a string by help of a character that is treated as a separator. In the program below the list elements have hyphen as their separator between letters and text. We will use that along with a for loop to capture each

Example

 Live Demo

listA = ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7'] # Given list print["Given list : " + str[listA]] # Extracting numbers num_list = [int[i.split['-'][1]] for i in listA] # print result print["List only with numbers : ",num_list]

Output

Running the above code gives us the following result −

Given list : ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7'] List only with numbers : [2, 8, 2, 7]

With map and isnumeric

In this approach we go through each element and check for the numeric part present in each element. The map function is used to apply the same function repeatedly on each of the element.

Example

listA = ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7'] # Given list print["Given list : " + str[listA]] # Extracting numbers num_list = list[map[lambda sub:int[''.join[ [i for i in sub if i.isnumeric[]]]], listA]] # print result print["List only with numbers : ",num_list]

Output

Running the above code gives us the following result −

Given list : ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7'] List only with numbers : [2, 8, 2, 7]

Published on 05-May-2020 10:13:43

This tutorial explains how to get numbers from a string in Python. It also lists some example codes to further clarify the concept using different approaches.

Numbers from a string can be obtained by simple list comprehension. split[] method is used to convert string to a list of characters and isdigit[] method is used to check if a digit is found through the iteration.

A basis code example is given as:

temp_string = "Hi my age is 32 years and 250 days12" print[temp_string] numbers = [int[temp]for temp in temp_string.split[] if temp.isdigit[]] print[numbers]

Output:

Hi my age is 32 years and 250 days12 [32, 250]

However, this code does not identify numbers that come with alphabets.

The re module of Python also provides functions that can search through the string and extract results. The re module provides with the findall[] method that returns a list of all the matches. An example code is given below:

import re temp_string = "Hi my age is 32 years and 250.5 days12" print[temp_string] print[[float[s] for s in re.findall[r'-?\d+\.?\d*', temp_string]]]

Output:

Hi my age is 32 years and 250.5 days12 [32.0, 250.5, 12.0]

The RegEx solution works for negative and positive numbers and overcomes the problem encountered in the List Comprehension approach.

DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python String

  • Count the Occurrence of a Character in a String in Python
  • Compare Strings in Python
  • report this ad

    Here, we will develop a program to extract numbers from string in python. If the string has “There are 5 pens for 2 students” then the extract numbers will be [5, 2]. We will also develop how to extract digits from string in Python. If the string has “kn4ow5pro8am2” then the extract numbers will be 4582. We are using List comprehension, isdigit[], str.split[], join[], filter[] methods and Regular Expression.

    Get Number from String Python

    We will take a string while declaring the variable. The For Loop extract number from string using str.split[] and isdigit[] function. The split function to convert string to list and isdigit function helps to get the digit out of a string. If so, use int[x] with the word as x to convert it to an integer. Then call list.append[object] with the integer as the object to append it to an output list.

    # Python program to extract number from string # take string string = "2 Java developer and 5 Python developer" # print original string print["The original string:", string] # using str.split[] + isdigit[] num = [] for i in string.split[]: if i.isdigit[]: num.append[int[i]] # print extract numbers print["Extract Numbers:", num]

    Output:-

    The original string: 2 Java developer and 5 Python developer
    Extract Numbers: [2, 5]

    Extract Integer from String Python

    This program method is similar to the above method, but rather a shorthand method. In this program we uses the list comprehension technique. The list comprehension which can help us iterating through the list.

    # Python program to extract number from string # take string string = "2 Java developer and 5 Python developer" # print original string print["The original string:", string] # using List comprehension + isdigit[] +str.split[] num = [int[i] for i in string.split[] if i.isdigit[]] # print extract numbers print["Extract Numbers:", num]

    Output:-

    The original string: 2 Java developer and 5 Python developer
    Extract Numbers: [2, 5]

    Note:- This program is not recognize floats, negative integers, or integers in hexadecimal format.

    Find Number in String Python

    In this program, we are using Regular Expression [RegEx module] to extract numbers from string in python. We can use the findall function to check for the numeric occurrences using matching regex string.

    # Python program to extract number from string # importing RegEx module import re # take string string = "2 Java developer and 5 Python developer" # print original string print["The original string:", string] # using re.findall[] methods temp = re.findall[r'\b\d+\b', string] num = list[map[int, temp]] # print extract numbers print["Extract Numbers:", num]

    Output:-

    The original string: 2 Java developer and 5 Python developer
    Extract Numbers: [2, 5]

    Extract Digits from String Python

    The filter[] function filters the digits detected in string by the isdigit[] function and join[] function performs the task of reconstruction of join function.

    # Python program to extract digits from string # take string string = "kn4ow5pro8am2" # print original string print["The original string:", string] # using join[] + filter[] + isdigit[] num = ''.join[filter[lambda i: i.isdigit[], string]] # print extract digits print["Extract Digits:", num]

    Output:-

    The original string: kn4ow5pro8am2
    Extract Digits: 4582

    Python get int from String

    In this program, we are using Regular Expression [RegEx module] to extract digits from strings. We can define the digit type requirement, using “\D”, and only digits are extracted from the string.

    # Python program to extract digits from string # importing RegEx module import re # take string string = "kn4ow5pro8am2" # print original string print["The original string:", string] # using re.sub[] methods num = re.sub["\D", "", string] # print extract digits print["Extract Digits:", num]

    Output:-

    The original string: kn4ow5pro8am2
    Extract Digits: 4582

    Also See:- Check if String Starts with Vowel

    If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

    Video liên quan

    Chủ Đề