Extract numbers from string list Python
PythonServer Side ProgrammingProgramming Show 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 splitThe 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 ExampleLive 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)OutputRunning 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 isnumericIn 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. ExamplelistA = ['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)OutputRunning 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 StringHere, 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 PythonWe 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 Integer from String PythonThis 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 Note:- This program is not recognize floats, negative integers, or integers in hexadecimal format. Find Number in String PythonIn 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. Output:- The original string: 2 Java developer and 5 Python developer Extract Digits from String PythonThe 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 Python get int from StringIn 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 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! |