1

Say I have a string like

"There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)"  

I want to be able to dynamically extract the numbers into a list: [34, 0, 4, 5].
Is there an easy way to do this in Python?

In other words,
Is there some way to extract contiguous numeric clusters separated by any delimiter?

3
  • Possible dup stackoverflow.com/questions/4289331/… Commented Apr 1, 2013 at 15:10
  • If the string were "12.34", would you want [12, 34] or [12.34]? IOW, is it only contiguous-digit integers you want? Commented Apr 1, 2013 at 15:15
  • In this case it would be [12, 34], integers. The current answer works as desired (I just can't accept it yet) Commented Apr 1, 2013 at 15:18

2 Answers 2

7

Sure, use regular expressions:

>>> s = "There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)"
>>> import re
>>> list(map(int, re.findall(r'[0-9]+', s)))
[34, 0, 4, 5]
Sign up to request clarification or add additional context in comments.

7 Comments

Using a list comprehension is usually preferable to using map. Especially since you're just casting the result to a list anyway.
@Cairnarvon It usually is, except if you can simply call an existing function (because then you don't have to figure out the name of a temporary variable). The list creation is just for the nice output. If you were to iterate over the result, you could obviously skip it.
You could have use \d+ for the regex too.
@Schoolboy Yes, but then one would have to use something significantly more complicated than int to support inputs like ٣٤.
@phihag Why is that?? how will those inputs get through the filter??
|
2

You can also do this without regular expressions, although it requires some more work:

>>> s = "There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)"
>>> #replace nondigit characters with a space
... s = "".join(x if x.isdigit() else " " for x in s)
>>> print s
                   34   0                      4 5
>>> #get the separate digit strings
... digitStrings = s.split()
>>> print digitStrings
['34', '0', '4', '5']
>>> #convert strings to numbers
... numbers = map(int, digitStrings)
>>> print numbers
[34, 0, 4, 5]

2 Comments

I think I like this even better than the itertools.groupby solution I was going to propose.
This is a great solution too

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.