繁体   English   中英

我如何计算字符串中的浮点数,将浮点数识别为一个数字? -Python

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

我有一串这样的数字,用空格隔开

test_string = '2.02.02.02.02.02.02.02.0'

当我执行len(lest_string)时,它返回24,表示正在计算小数点和小数位。 如何计算字符串中的元素,以使2.0被计为1个元素而不是3个元素?

您可以尝试以下方法:

test_string = '2.02.02.02.02.02.02.02.0' 

print test_string.count("2.0")

输出:

8

如果在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())

如果您的数字实际上用空格分隔,则可以

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

另外,如果您确定数字之间永远只有一个空格,

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

或者你可以

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

在您的test_string ,数字不是用空格分隔的。 如果是,则可以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)

返回:

Debug: l = 8

test_string = '2.02.02.02.02.02.02.02.0'

要么

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

输出:8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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