I'd use a regexp:
>>> import re
>>> re.findall(r'\d+', "hello 42 I'm a 32 string 30")
['42', '32', '30']
This would also match 42 from bla42bla. If you only want numbers delimited by word boundaries (space, period, comma), you can use \b:
>>> re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")
['42', '32', '30']
To end up with a list of numbers instead of a list of strings:
>>> [int(s) for s in re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")]
[42, 32, 30]
NOTE: this does not work for negative integers
Answer from Vincent Savard on Stack OverflowI'd use a regexp:
>>> import re
>>> re.findall(r'\d+', "hello 42 I'm a 32 string 30")
['42', '32', '30']
This would also match 42 from bla42bla. If you only want numbers delimited by word boundaries (space, period, comma), you can use \b:
>>> re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")
['42', '32', '30']
To end up with a list of numbers instead of a list of strings:
>>> [int(s) for s in re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")]
[42, 32, 30]
NOTE: this does not work for negative integers
If you only want to extract only positive integers, try the following:
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]
I would argue that this is better than the regex example because you don't need another module and it's more readable because you don't need to parse (and learn) the regex mini-language.
This will not recognize floats, negative integers, or integers in hexadecimal format. If you can't accept these limitations, jmnas's answer below will do the trick.
Is there a better way to extract numbers from a string in python 3 - Stack Overflow
python 3.x - Extract a number after a particular string - Software Engineering Stack Exchange
How to extracts number from this python list
Extract Numbers from Within Strings in Pandas Column
Hi I am new to Python but am working on a project where I want to extract numbers from a string. For example I have the string "CORSAIR VENGEANCE RGB 16GB (2X8GB) DDR4 3200MHZ CL 16" where I want to extract the "16" from "16GB" as well as the "2" and "8" in "(2x8GB)" and "3200" from "3200MHZ".
What is the best way to do this? Thanks in advance!
Edit: Thanks everyone for the help! Regex seems to help do the trick
Regular expressions to the rescue!
I see you are already on the right path, by using a regular expression. But you could try using a regular expression with a capture in order to capture the digits following the string "Episode".
Here is a small example to get you going:
import re
m = re.search('Episode (\d+)', 'series[Episode 37]-03th_July_2010-YouTube', re.IGNORECASE)
m.group(1)
The last statement, m.group(1), returns the contents of the first group (what's inside the parentheses in the regular expression). In this case it will be the string '37', which is the digits that follows the string "Episode ".
Also notice I'm using the IGNORECASE flag, so this will work regardless of the casing of the string "Episode". So "episode" and even "ePISODE" will work too.
Kind of broad, pulling from a text file, but will do for many applications of getting both integers and floats out of strings.
The file, commaseperated.txt has a row looking like this:
Input: (0, 1, 2.4), 1, 5, 8, 99.7, 0.1), (, )()!@!#, 9
import re
# a function to pull the numbers from many lists of strings
def func(a, z, c):
# -- Read .txt -- #
filename = 'commaseperated.txt'
f1 = open(filename, 'r') # open the file for reading
data = f1.readlines() # read the entire file as a list of strings
f1.close()
#
for line in data:
cells = line.strip().split(',')
# empty string
b = ""
# range through cells of from a text file split by commas
for i in range(a, len(cells[z:c])+a):
# no commas in the cells so make dummy commas for new string
b += cells[i] + ','
# find all the numbers
z = re.findall(r'\d+(?:\.\d+)?', b)
# return a list of floated values from the text string
return [float(z[s]) for s in range(len(z))]
Output: [0, 1, 2.4, 1, 5, 8, 99.7, 0.1, 9]