簡體   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