2016-12-13 35 views
1

我是一名中級Python程序員。在我的實驗,我使用Linux命令輸出的一些結果是這樣的:使用陣列切片時的問題

OFPST_TABLE reply (xid=0x2): 
    table 0 ("classifier"): 
    active=1, lookup=41, matched=4 
    max_entries=1000000 
    matching: 
     in_port: exact match or wildcard 
     eth_src: exact match or wildcard 
     eth_dst: exact match or wildcard 
     eth_type: exact match or wildcard 
     vlan_vid: exact match or wildcard 
     vlan_pcp: exact match or wildcard 
     ip_src: exact match or wildcard 
     ip_dst: exact match or wildcard 
     nw_proto: exact match or wildcard 
     nw_tos: exact match or wildcard 
     tcp_src: exact match or wildcard 
     tcp_dst: exact match or wildcard 

我的目標是收集參數active=這是不時變量的值(在這種情況下,它僅僅是1)。我用下面的切片,但它不工作:

string = sw.cmd('ovs-ofctl dump-tables ' + sw.name) # trigger the sh command 
count = count + int(string[string.rfind("=") + 1:]) 

我想我用切片錯在這裏,但我嘗試過很多辦法,但我還是什麼也沒得到。有人可以幫我從這個字符串中提取active=參數的值嗎?

非常感謝:)

回答

2

regex怎麼樣?

import re 
count += int(re.search(r'active\s*=\s*([^,])\s*,', string).group(1)) 
+0

非常感謝你..工作非常整齊.. :) –

2

1)使用正則表達式:

import re 
m = re.search('active=(\d+)', ' active=1, lookup=41, matched=4') 
print m.group(1) 

2)str.rfind返回,其中子被發現的最高指數字符串中,它會找到=(最右邊的matched=4),即不是你想要的。 3)簡單的切片不會對你有所幫助,因爲你需要知道活動值的長度,總體來說它不是這項任務的最佳工具。

+0

謝謝澄清。 –