how to seperate numbers from a string optimally

Viewed 66

I'd like to remove strings in my list.
Suppose,
x = ['feature 1' , 'feature 2' , 'feature 3' , 'feature 4']

I want to achieve,
x = [1, 2, 3, 4]

I know this can be achieved by splitting each individual element and removing the feature term and retaining the remaining value.

BUT

i want to create a common function to achieve something like this and more optimal function rather than extracting each indiviual element and doing it.. It's cumbersome.

INSTEAD

I want a solution which auto detects the strings and removes it in each element.

NOW THAT'S OPTIMAL
Please let me know below if there's anything like it.

2 Answers

This function should help you to do what you require:

import re
x = ['feature 1' , 'feature 2' , 'feature 3' , 'feature 4']

def remove_strings(x):
    y = [int(re.findall('\d+', i)[0]) for i in x]
    return y

remove_strings(x)

Hope this helps :)

newlist = []
def liststringtoint(list1):
    for word in list1:
        for letter in word:
            if letter.isnumeric():
                letter = int(letter)
                newlist.append(letter)
Related