0

I have a list in Python that looks like this:

['29382 this is something', '2938535 hello there', '392835 dont care for this', '22024811 yup']

I need to process it so that it like this:

['29382', '2938535', '392835', '22024811']

How would I go on about doing this? I guess I could use re, but I don't know how to apply it in this situation.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
agh
  • 13
  • 2
  • StackOverflow is around to help you with your implementation. Please, show us what you attempted to do, or ideas you had, especially if you can include some code. – seebiscuit Dec 29 '14 at 15:13

2 Answers2

3

You do not need regex for this, you can use split within a list comprehension.

>>> l = ['29382 this is something', '2938535 hello there', '392835 dont care for this', '22024811 yup']

>>> [i.split(' ', 1)[0] for i in l]
['29382', '2938535', '392835', '22024811']
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Thank you for that! It does the job, but I don't quite understand how it works. – agh Dec 29 '14 at 15:08
  • @Michel What confuses you, the `split` function or the list comprehension? – Cory Kramer Dec 29 '14 at 15:08
  • @Cyber The list comprehension – agh Dec 29 '14 at 15:09
  • @Michel A list comprehension is essentially just a concise way to replace a `for` loop. [See here](http://www.pythonforbeginners.com/basics/list-comprehensions-in-python). They are very powerful, clean, and pythonic so they are definitely worth learning. – Cory Kramer Dec 29 '14 at 15:11
1

Something like

>>> l=['29382 this is something', '2938535 hello there', '392835 dont care for this', '22024811 yup']
>>> import re
>>> [ re.sub(r'\D', '', x) for x in l]
['29382', '2938535', '392835', '22024811']
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52