1

Is there any efficient way to find count of int and float in string, without using two different list comprehension

st = '2.00 00 DBEL 215 Frox Lyxo 2.000 2.00'

reg = r'\d+(?:\.\d*)?'

out = re.compile(reg).findall(st)

# output as  ['2.00', '00', '215', '2.000', '2.00']

int_in_string = len([i for i in out if isinstance(eval(str(i)), int)])
fl_in_string = len([i for i in out if isinstance(eval(str(i)), float)])

print('no of int : ', int_in_string, 'no of float : ', fl_in_string)
utks009
  • 573
  • 4
  • 14

4 Answers4

2

Take a look at the following:

st = '2.00 00 DBEL 215 Frox Lyxo 2.000 2.00'

floats, ints = 0, 0
for word in st.split():
    try:
        int(word)
    except ValueError:
        try:
            float(word)
        except ValueError:
            pass
        else:
            floats += 1
    else:
        ints += 1

print('no of int : ', ints, 'no of float : ', floats)  # no of int :  2 no of float :  3

My code takes a different approach. regex is not used. The string is split on whitespace and the individual words are cast to float and int inside try-blocks. If the tries are successful (else-part of the block), a counter is increased.

Ma0
  • 15,057
  • 4
  • 35
  • 65
0

You don't need to actually save the numbers again on int_in_string and fl_in_string, so you could use two simple counters

int_in_string = 0
fl_in_string   = 0
for i in out:
    if isinstance(eval(str(i)), int):
        int_in_string += 1
    elif isinstance(eval(str(i)), float):
        fl_in_string += 1
0

If all your ints follow the pattern \d+ and all your floats follow the pattern \d+\.\d+, you can count them as follows

>>> num_ints = sum(1 for _ in re.finditer(r'(?<=\W)\d+(?=\W)', st))
>>> num_floats = sum(1 for _ in re.finditer(r'(?<=\W)\d+\.\d+(?=\W)', st))
>>> print (num_ints, num_floats)
6 1
Sunitha
  • 11,777
  • 2
  • 20
  • 23
0

Assuming regex is NOT a must.

st = '2.00 00 DBEL 215 Frox Lyxo 2.000 2.00'
s = [i.isdigit() for i in st.split(' ') if not(i.isalpha())]
print('no of int : ', s.count(True), 'no of float : ', s.count(False))
LChiu
  • 1
  • 1