Home > database >  Edit elements of the list
Edit elements of the list

Time:06-23

I have a list called ids:

ids = ['id = 1234', 'id=223345', 'id=456', 'id=4562347', 'id=521345678']

How to create new list in python that contains only numbers like:

new_ids=['1234', '223345', '456', '4562347', '521345678'] 

CodePudding user response:

You can use split() and replace() functions to get the list without any text:

ids = ['id = 1234', 'id=223345', 'id=456', 'id=4562347', 'id=521345678']
print([i.split("=")[1].replace(" ", "") for i in ids])

Output:

['1234', '223345', '456', '4562347', '521345678']

Also, you can achieve the same result by using regular expressions as follows:

import re

ids = ['id = 1234', 'id=223345', 'id=456', 'id=4562347', 'id=521345678']
print([re.sub("[^0-9]", "", i) for i in ids])

CodePudding user response:

You can use regex:

import re 
new_ids = [re.findall(r'\d ', id) for id in ids]

CodePudding user response:

you can do it by list comprehension using strip to remove the spaces:

new_ids = [x[-1].strip() for x in ids]

if you want to convert them to int type you can do it right away in the list comprehension:

new_ids = [int(x[-1].strip()) for x in ids]

you could do it also by map but i don't raccomend it because it is slower and the list comprehension is more readable

new_ids = list(map(lambda x:int(x[-1].strip()),ids))

and also there is the regex way wich is the slowest but if you prefer it you can use it

import re as regex
new_ids = [regex.search(r'(\d )',x).string for x in ids]
  • Related