3

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.

3
  • 4
    re.findall("\d+",str(x)) I guess would probably do what you want Commented Jun 20, 2020 at 6:07
  • Wow, that worked like a charm. Thank You! Commented Jun 20, 2020 at 6:17
  • Thank you, but @Joran Beasley code above is more optimal i think. Commented Jun 20, 2020 at 6:20

2 Answers 2

1

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 :)

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Good work! But i want the resultant list to be inline without creating new list.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.