artk
artk

Reputation: 11

How to calculate the number of integers in a python string

I want to calculate the number of integers in the string "abajaao1grg100rgegege". I tried using isnumeric() but it considers '100' as three different integers and shows the output 4. I want my program to consider 100 as a single integer.

Here is my attempt:

T = int(input()) 
for x in range(T): 
    S = input() 
    m = 0 
    for k in S: 
        if (k.isnumeric()): 
            m += 1 
print(m)

Upvotes: 0

Views: 79

Answers (5)

Chirag
Chirag

Reputation: 1

random="1qq11q1qq121a21ws1ssq1";
counter=0
i=0
length=len(random)
while(i<length):
  if (random[i].isnumeric()):
    z=i+1
    counter+=1
    while(z<length):
      if (random[z].isnumeric()):
        z=z+1
        continue
      else:
        break
    i=z
  else:
    i+=1
print ("No of integers",counter)

Upvotes: 0

steliosbl
steliosbl

Reputation: 8921

Regex is the go-to tool for this sort of problem, as the other answers have noted. However, here is a solution that uses looping constructs and no regex:

result = sum(y.isdigit() and not x.isdigit() for x,y in zip(myString[1:], myString))

In addition, here is an easy to understand, iterative solution, that also doesn't use regex and is much more clear than the other one, but also more verbose:

def getNumbers(string):
    result = 0
    for i in range(len(string)):
        if string[i].isdigit() and (i==0 or not string[i-1].isdigit()):
            result += 1
    return result

Upvotes: 1

MarianD
MarianD

Reputation: 14131

Not very Pythonic but for beginners more understandable:

Loop over characters in string and in every iteration remember in the was_digit (logical variable) if the current character is digit - for the next iteration.

Increase the counter only if the previous character was not a digit:

string = 'abajaao1grg100rgegege'
counter = 0                   # Reset the counter
was_digit = False             # Was previous character a digit?

for ch in string:
    if ch.isdigit():
        if not was_digit:     # previous character was not a digit ...
            counter += 1      # ... so it is start of the new number - count it!
        was_digit = True      # for the next iteration
    else:
        was_digit = False     # for the next iteration

print(counter)                # Will print 2

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81594

I'd use a very basic regex (\d+) then count the number of matches:

import re

string = 'abajaao1grg100rgegege'
print(len(re.findall(r'(\d+)', string)))
# 2

Upvotes: 2

omri_saadon
omri_saadon

Reputation: 10631

You can use the regex library to solve this issue.

import re
st = "abajaao1grg100rgegege"
res = re.findall(r'\d+', st)

>>> ['1', '100']

You can check how many numbers you have on that list that the findall returned.

print (len(res))
>>> 2

In order to read more on python regex and the patterns, enter here

Upvotes: 1

Related Questions