2013-04-23 47 views
0

我有一個像如何得到一個數組的索引lenth在python

  for i in re.finditer('something(.+?)"', html): 

我現在想一個Python代碼,找出它有多少次去循環纔去那loop..in其他單詞i的長度。 任何人都可以給我一個替代但類似的代碼與我得到循環的長度。

+2

你能詳細說明爲什麼你需要事先知道長度嗎? – georg 2013-04-23 09:03:00

+0

我想用百分比顯示活動的進度。 – 2013-04-23 10:31:33

回答

3
x = list(re.finditer('something(.+?)"', html)) 

if len(x) 
    .... 

for i in x: 
    .... 

findall不是一個適當的替代,因爲它返回一個字符串,不匹配的對象。

1

你不能做到這一點與re.finditer,因爲它返回一個迭代時,它的完成,直到它(因爲它發現在每次迭代的下一場比賽)......不知道,你得使用re.findall

matches = re.findall('something(.+?)"', html) 
num_loops = len(matches) 

或者使用@ thg435的方法,如果您確實需要匹配對象。

+0

如何實現re.findall以及獲取索引號? – 2013-04-23 08:59:11

+1

@Abul Hasnat你只需在列表中使用'len(..)'。如果你想要每個匹配的索引號,那麼在枚舉(re.findall(...))中輸入'for i,m' – jamylak 2013-04-23 09:01:39

1

finditer返回結果,因爲它發現它們。 finditer沒有辦法告訴你你會提前循環多少次。

您需要使用別的東西。無論是re.findall或可能re.search拿到長度

相關問題