-2

I'm just getting back into python and was wondering if there is an easy way to return the number of integers that exist in a given string.

For example if I had a list,

['1 5','2 10 23','214 33 1']

iterating through each item in the list and finding the number of integers would return 2, 3, and 3, respectively.

The only thing I can think of would be to have a 2-dimensional list, where each item in the main list is another list that holds the separate numbers, and then I could call len() on each secondary list. Is there an easier way?

Dyrborg
  • 877
  • 7
  • 16
johnsmith101
  • 179
  • 1
  • 2
  • 11

2 Answers2

1

Just use a list comprehension. This requires that integers are split by a space ' ' in your list of strings.

data = ['1 5','2 10 23','214 33 1']
int_per_string = [len(x.split(' ')) for x in data]

Returns:

Out[8]:[2, 3, 3]
Nathan Clement
  • 1,103
  • 2
  • 18
  • 30
0

According to the example you kept, for each item in your list they were separated with spaces. So you can try using .isdigit()

    numCount=[]
    for item in list:
        index=0
        sublist = item.split()
        for subitem in sublist:
            if subitem.isdigit():
                index +=1
        numCount.append(index)
    print(numCount)

I hope this will help you. You can also use subitem.isalnum() instead of subitem.isdigit() if you want to check for a number which is included along with a string.

Thank you.

Strik3r
  • 1,052
  • 8
  • 15