Home > Mobile >  Find "n" in a list full of strings
Find "n" in a list full of strings

Time:11-30

I'm looking to go through a list and find any element with a number.

This is what i got so far

list = ['Alvarez, S', 'Crawford, B', 'Fury, 8', 'Mayweather, F', 'Lopez, 44']

num = '8'

for s in home_pitchers:
    if num in s:
        print(s)

print(ex)
>>> Fury, 8

What I'm looking to do is to have num be 0 - 9. I thought about using '[^0-9]' but that didn't work.

Ultimately I'm looking to print out this

print
>>> Fury, 8
>>> Lopez, 44

Just a heads up, I'm pretty new to coding so some concept might go over my head

CodePudding user response:

You can use isdigit method with any function. The isdigit method return True if the string is a digit string, False otherwise.

>>> lst = ['Alvarez, S', 'Crawford, B', 'Fury, 8', 'Mayweather, F', 'Lopez, 44']
>>>
>>> for s in lst:
...     if any(char.isdigit() for char in s):
...             print(s)
...
Fury, 8
Lopez, 44

CodePudding user response:

Using the re library:

import re

lst = ['Alvarez, S', 'Crawford, B', 'Fury, 8', 'Mayweather, F', 'Lopez, 44']

list(filter(lambda x:re.match(".*[0-9] $",x), lst))

OUTPUT:

['Fury, 8', 'Lopez, 44']

The pattern matches any string ending with one or more numbers.

  • Related