[英]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. 当我执行len(lest_string)时,它返回24,表示正在计算小数点和小数位。 How do I count the elements in the string such that 2.0 is counted as 1 element and not 3 elements?
如何计算字符串中的元素,以使2.0被计为1个元素而不是3个元素?
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中提供了空格:
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. 在您的
test_string
,数字不是用空格分隔的。 If they were, you could split()
the test_string
and get the length of the resulting list: 如果是,则可以
split()
test_string
并获取结果列表的长度:
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 输出:8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.