0

I have following values stored in a string variable 'id'.

map00010
map00020
map00030
map00040
map00051
map00052
map00053
map00061

I would like to extract only the numerical values and store it in a list.

I am trying following line in my code:

print(id[3:].split())

But I am getting following output:

['00010']
['00020']
['00030']
['00040']
['00051']
['00052']
['00053']
['00061']

The expected output is:

list = [00010, 00020, 00030, 00040, 00051, 00052, 00053, 00061]

Any help is highly appreciated

rshar
  • 1,381
  • 10
  • 28
  • `print([i[3:] for i in id.split()])` use this – Davinder Singh Apr 01 '21 at 20:44
  • Does this answer your question? [Convert all strings in a list to int](https://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int) – baduker Apr 01 '21 at 20:46
  • 1
    Do you expect to keep this as strings, or as integers? Because if you convert to integer, you'll get [10,20,30,40,51,52,53,61]. There are no leading zeros in an integer representation. – Tim Roberts Apr 01 '21 at 20:46
  • Does this answer your question? [How to make a flat list out of a list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) – peer Apr 01 '21 at 20:47

4 Answers4

1

if the above in question is a string you can create a list by

a = """map00010
map00020
map00030
map00040
map00051
map00052
map00053
map00061"""

lst = a.split()

once you have a list use a list comprehension and string slicing

lst2 = [item[3:] for item in lst]
print(lst2)

returns:

['00010', '00020', '00030', '00040', '00051', '00052', '00053', '00061']
Mirronelli
  • 740
  • 5
  • 14
0

Check out this code:

id = '''map00010
map00020
map00030
map00040
map00051
map00052
map00053
map00061'''

print([i[3:] for i in id.split()])

Output:

['00010', '00020', '00030', '00040', '00051', '00052', '00053', '00061']

METHOD-2: Using Regex

import re
regobj = re.compile(r'\d+')

l = regobj.findall(id)
print(l)
Davinder Singh
  • 2,060
  • 2
  • 7
  • 22
0

Try the following:

id = """map00010
map00020
map00030
map00040
map00051
map00052
map00053
map00061"""

lst = []
for item in id.split("\n"):
    lst.append(item[3:])

print(lst)

I don't know exactly how your string is formatted, but from your question, it seems as if they are separated by a "\n" newline character.

Dugbug
  • 454
  • 2
  • 11
0

you haven't clearly mentioned what your input variable is, if it's a string like:

string = "map00010 map00020 map00030 map00040 map00051 map00052 map00053 map00061"

you can use:

res = [x[3:] for x in string.split()]
print(res)

output:

['00010', '00020', '00030', '00040', '00051', '00052', '00053', '00061']
Vedank Pande
  • 436
  • 3
  • 10