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?
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With