-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
  • 51
  • 1
  • 7

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
  • 49,704
  • 8
  • 81
  • 106
0

Use regular expressions:

import re
num_list = [re.search(r'\d+', x)[0] for x in mylist]
Kamyar
  • 2,494
  • 2
  • 22
  • 33
-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,321
  • 1
  • 10
  • 15