5

So I have this list of strings:

teststr = ['1 FirstString', '2x Sec String', '3rd String', 'x forString', '5X fifth']

What I need to do, is to get all the elements from this list that contain:

number + "x" 

or

number + "X"

For example if I have the function

def SomeFunc(string):
    #do something

I would like to get an output like this:

2x Sec String
5X fifth

I found somewhere here in StackOverflow this function:

def CheckIfContainsNumber(inputString):
    return any(char.isdigit() for char in inputString)

But this returns each string that has a number.

How can I expand the functions to get the desired output?

1 Answer 1

9

Use re.search function along with the list comprehension.

>>> teststr = ['1 FirstString', '2x Sec String', '3rd String', 'x forString', '5X fifth']
>>> [i for i in teststr if re.search(r'\d+[xX]', i) ]
['2x Sec String', '5X fifth']

\d+ matches one or more digits. [xX] matches both upper and lowercase x.

By defining it as a separate function.

>>> def SomeFunc(s):
        return [i for i in s if re.search(r'\d+[xX]', i)]

>>> print(SomeFunc(['1 FirstString', '2x Sec String', '3rd String', 'x forString', '5X fifth']))
['2x Sec String', '5X fifth']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.