1

If I have an input string:

a = 'W1 W2 W3 W4 W5 W6 W7 W8 W9 W10 W11'

How to extract the numbers and store in a list? For example

numList = [1,2,3,4,5,6,7,8,9,10,11]

I have tried doing it like this:

[int(t) for t in a if t.isdigit()]

This only works for the single digit numbers, but doesn't work for the double digit numbers.

Sam
  • 13
  • 5

2 Answers2

2

You can split by space and then slice the first character of every item out:

>>> [int(item[1:]) for item in a.split()]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

You can also, if applicable (do not know the origin and possible variations of the input string), just remove the W from the string and split:

>>> a = a.replace("W", "")
>>> [int(item) for item in a.split()]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
0

You can do this with regex:

import re
numList = re.findall(r'\d+', a)
Andrew LaPrise
  • 3,373
  • 4
  • 32
  • 50