Efficient way to count number of int and float in string using Python

python count number of digits in string
python get digits of number
find out how many times a particular digit occurs in a number in python
find the number of occurrences of a given digit in a number in python
how to count inputs in python
how to count up to a number in python
python get number of digits in float
how to count numbers in python

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)

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.

Count number of digits in a number in Python, Solution 2 ( Using inbuilt methods ) : Instead of using a while loop, we can directly convert the integer to a string and get the length of the string. In  Convert string to int or float Python | string to number. Convert string to int Python is different from other programming languages like Java, c and etc. Python doesn’t implicitly typecast strings to Integer(numbers). Python has standard built-in int()and functionfloat( ) is to convert a string into an integer or float value.


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

Data Types and Type Conversion – Plotting and Programming in , Use built-in functions to convert between integers, floating point numbers, and strings. Types control what operations (or methods) can be performed on a given value. The built-in function len counts the number of characters in a string. What type of value (integer, floating point number, or character string) would you  Floats have unlimited length as well, but a floating-point number must contain a decimal point. Complex numerics must have an imaginary part, which is denoted using j: >>> integerFirst = 23 >>> floatFirst = 23.23 >>> complextFirst = 1 + 23j Converting Strings to Numerics Using the int() Function. If you want to convert a string to an integer, the simplest way would be to use int() function. Just pass the string as an argument:


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

4. Built-in Types, There are three distinct numeric types: integers, floating point numbers, and complex numbers. can add to an integer or float to get a complex number with real and imaginary parts. Negative shift counts are illegal and cause a ValueError to be raised. Two methods support conversion to and from hexadecimal strings. Floats with very big or very small absolute value can be written using a scientific notation. Eg., the distance from the Earth to the Sun is 1.496·10 11, or 1.496e11 in Python. The mass of one molecule of the water is 2.99·10-23, or 2.99e-23 in Python. One can cast float objects to int objects by discarding the fraction part using the int


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))

5. Built-in Types, Floating point numbers are usually implemented using double in C; information about the you can add to an integer or float to get a complex number with real and imaginary parts. Negative shift counts are illegal and cause a ValueError to be raised. Two methods support conversion to and from hexadecimal strings​. In the output, you can see a flat integer value. The same can be applied as converting a string to float. The example of using base argument for string to int. As such, you may also use the Python int function as follows: class int(x, base=10) That means you may provide base value for conversion as well.


5. Built-in Types, There are three distinct numeric types: integers, floating point numbers, and complex numbers. can add to an integer or float to get a complex number with real and imaginary parts. Negative shift counts are illegal and cause a ValueError to be raised. Two methods support conversion to and from hexadecimal strings. Last print statement prints the number of digits present in the given number using the Count variable as the output. So, the output of the given variable 9875 is 4. Python Program to Count Number of Digits in a Number Using Functions. This Python program allows the user to enter any positive integer. Then it divides the given number into individual digits and counting those individual digits using Functions.


2. Built-in Functions, For more information on class methods, consult the documentation on the standard by enumerate() returns a tuple containing a count (from start which defaults to 0) and Return a floating point number constructed from a number or string x. Create one counter variable to hold the total number count. Initialize this variable to zero at the start of the program. 3. Using a while loop, delete the rightmost digit of the number or convert the number to this new number. For example, if the number is 123, convert it to 12, then convert it to 1 and finally 0.


Python Intro for Libraries: Data Types and Type Conversion, Use built-in functions to convert between integers, floating point numbers, and strings. Types control what operations (or methods) can be performed on a given value. The built-in function len counts the number of characters in a string. What type of value (integer, floating point number, or character string) would you  Improve your Python with our efficient tips and tricks. The following are the tips every Python programmer should know. You can Practice tricks using Online Code Editor. Tip and Trick 1: How to measure the time elapsed to execute your code in Python. Let’s say you want to calculate the time taken to complete the execution of your code.