Summary: To extract numbers from a given string in Python you can use one of the following methods:,Thus to solve our problem we must import the regex module which is already included in Pythons standard library and then with the help of the findall() function we can extract the numbers from the given string. ,Another workaround for our problem is to split the given string using the split() function and then extract the numbers using the built-in float() method then append the extracted numbers to the list. ,Since the Numbers from String library is not a part of the standard Python library, you have to install it before being able to use it. Use the following command to install this useful library:
Given is the following string:
Extract 100, 1000 and 10000 from this string
This is your desired output:
[100, 1000, 10000]
Let us have a look at the following code to understand how we can use the regex
module to solve our problem:
import re
sentence = 'Extract 100 , 100.45 and 10000 from this string'
s = [float(s) for s in re.findall(r '-?\d+\.?\d*', sentence)]
print(s)
Now that we have the necessary tools to solve our problem based on the above concept, let us dive into the code to see how it works:
sentence = 'Extract 100 , 100.45 and 10000 from this string'
s = []
for t in sentence.split():
try:
s.append(float(t))
except ValueError:
pass
print(s)
Let us have a look at the code given below to see how the above concept works:
sentence = 'Extract 100 , 100.45 and 10000 from this string'
s = [int(s) for s in str.split(sentence) if s.isdigit()]
print(s)
There are a number of ways to convert the list from a collection of string
to int
types. The first thing I would note, however, is this: don't iterate twice over the list if you don't have to. When you're iterating, read the data in, convert it to the type, and append it:
for line in data.readlines():
new_data.append(int(line.strip()))
This could be shortened by using a list comprehension or map
call:
new_data = map(int, data.readlines()) new_data = [int(line) for line in data.readlines()]
If you must iterate over it twice, you can use a list comprehension or map
to convert it:
no_data = [int(num) for num in new_data] # or no_data = map(int, new_data)
Simply take the UTF-8 string type input and use the built in int() function. I've made the necessary change to your code below. I've also made it so that you'll only iterate over the list of lines once, and simplified the flow of the program to be more easily understood.
lines = open('C:\file.txt', 'r').readlines()
new_data = []
for line in lines:
new_data.append(int(line.strip()))
print new_data
Last Updated : 27 Mar, 2019
The original string: There are 2 apples for 4 persons The numbers list is: [2, 4]
Python provides us with string.isdigit() to check for the presence of digits in a string.,Further, we we re.findall(r'\d+', string) to extract digit characters from the string. The portion ‘\d+’ would help the findall() function to detect the presence of any digit.,Python isdigit() function returns True if the input string contains digit characters in it.,Hello, readers! In this article, we will be focusing on the ways to extract digits from a Python String. So, let us get started.
string.isdigit()
inp_str = "Python4Journaldev"
print("Original String : " + inp_str)
num = ""
for c in inp_str:
if c.isdigit():
num = num + c
print("Extracted numbers from the list : " + num)
Original String: Python4Journaldev
Extracted numbers from the list: 4
inp_str = "Hey readers, we all are here be 4 the time!"
print("Original string : " + inp_str)
num = [int(x) for x in inp_str.split() if x.isdigit()]
print("The numbers list is : " + str(num))
Original string: Hey readers, we all are here be 4 the time! The numbers list is: [4]
import re
You can iterate through the string and use the string isdigit() function to extract numbers from a string in Python. Use the following steps –,Alternatively, you can use regular expressions to extract numbers from a string. Let’s use it to capture the digits in a string.,In this tutorial, we will look at how to extract numbers from a string in Python with the help of examples.,We get the numbers from the string in our result list. You can also capture contiguous digits using the r'\d+' regular expression.
Let’s look at an example to see the above steps in action in Python.
# string with numbers s = "I love you 3000" # result string s_nums = "" # iterate over characters in s for ch in s: if ch.isdigit(): s_nums += ch # display the result string print(s_nums)
Output:
3000
You can reduce the above code to a single line by using a list comprehension and the string join()
function.
# string with numbers s = "I love you 3000" # result string s_nums = "".join([ch for ch in s if ch.isdigit() ]) # display the result string print(s_nums)
Alternatively, you can use regular expressions to extract numbers from a string. Let’s use it to capture the digits in a string.
import re # string with numbers s = "I love you 3000" # result list s_nums = re.findall(r '\d', s) # display the result list print(s_nums) print("".join(s_nums))
Let’s look at an example.
import re # string with numbers s = "The temperature on the 27th of December was -5 degrees celsius." # result list s_nums = re.findall(r '-?\d+', s) # display the result list print(s_nums)
Python Exercises, Practice, Solution,Pandas DataFrame: Exercises, Practice, Solution,C Programming Exercises, Practice, Solution : Recursion,C++ Basic: Exercises, Practice, Solution
Python Code :
import pandas as pd
import re as re
pd.set_option('display.max_columns', 10)
df = pd.DataFrame({
'company_code': ['c0001', 'c0002', 'c0003', 'c0003', 'c0004'],
'address': ['7277 Surrey Ave.', '920 N. Bishop Ave.', '9910 Golden Star St.', '25 Dunbar St.', '17 West Livingston Court']
})
print("Original DataFrame:")
print(df)
def find_number(text):
num = re.findall(r '[0-9]+', text)
return " ".join(num)
df['number'] = df['address'].apply(lambda x: find_number(x))
print("\Extracting numbers from dataframe columns:")
print(df)
Sample Output:
Original DataFrame:
company_code address
0 c0001 7277 Surrey Ave.
1 c0002 920 N.Bishop Ave.
2 c0003 9910 Golden Star St.
3 c0003 25 Dunbar St.
4 c0004 17 West Livingston Court\ Extracting numbers from dataframe columns:
company_code address number
0 c0001 7277 Surrey Ave.7277
1 c0002 920 N.Bishop Ave.920
2 c0003 9910 Golden Star St.9910
3 c0003 25 Dunbar St.25
4 c0004 17 West Livingston Court 17
Membership Testing in a Collection:
>>> a = ('one', 'two', 'three', 'four', 'five') >>>
if 'one' in a:
...print('The tuple contains one.')
...
The tuple contains one. >>>
b = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three'
} >>>
if 2 in b.keys():
...print('The dict has the key of 2.')
...
The dict has the key of 2.