简体   繁体   中英

How can I count number of floating points in a string, recognizing the floating point as one number? - Python

I have a string of numbers separated by space like this

test_string = '2.02.02.02.02.02.02.02.0'

when I do len(lest_string), it returns 24, meaning it is counting the decimal point and decimal places. How do I count the elements in the string such that 2.0 is counted as 1 element and not 3 elements?

You can try this:

test_string = '2.02.02.02.02.02.02.02.0' 

print test_string.count("2.0")

Output:

8

If spaces are provided in the test_string:

test_string = '2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0'

print len(test_string.split())

If your numbers are actually separated by spaces you could do

test_string =  '2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0'
nums = [float(f) for f in test_string.split()]
how_many = len(nums)    # 8

Alternatively, if you are certain there is only ever exactly one space between numbers,

how_many = test_string.count(" ") + 1    # 8

or you could just

how_many = test_string.count(".")        # 8

In your test_string the numbers aren't separated by space. If they were, you could split() the test_string and get the length of the resulting list:

test_string = '2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0'
l = len(test_string.split())
print("Debug: l =", l)

Returns:

Debug: l = 8

test_string = '2.02.02.02.02.02.02.02.0'

or

test_string = '2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0'

count = len(re.findall(r'2.0', test_string))

output: 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM