-2

So I have list that looks like this

mylist = ['storeitem_1','storeitem_2','storeitem_3']

How would I go about getting only numbers from those strings? I tried following but it came out totally wrong.

for items in mylist:
  print(items.split("storeitem_"))

Any help is appreciated

Walnut
  • 41
  • 6

3 Answers3

0

Here is one way with a regex:

import re

mylist = ['storeitem_1','storeitem_2','storeitem_3']

re.findall('\d+', '|'.join(mylist))

Which gives:

['1', '2', '3']

Alternatively, something more along the lines of what you were trying:

[i.split('_')[-1] for i in mylist]

Gives you the same:

['1', '2', '3']
sacuL
  • 45,929
  • 8
  • 75
  • 99
0

Use regular expressions:

import re
num_list = [re.search(r'\d+', x)[0] for x in mylist]
Kamyar
  • 1,970
  • 1
  • 19
  • 32
-1

Assuming mylist always contains strings in the form of 'storeitem_n' where n is an integer from 0 to 9

You can do this to get n:

mylist = ['storeitem_1','storeitem_2','storeitem_3']

for items in mylist:
  print(items[-1])
bigwillydos
  • 1,241
  • 1
  • 9
  • 15