2016-12-25 95 views
2

我已經通過了關於該主題的每篇文章,並且沒有任何回覆我的問題;在Python上從字符串中提取整數值

這是代碼:
output = 'Scan results for BrainS (192.168.43.111) Scan results for Slave (192.168.43.107) Scan results for SlaveSmall (192.168.43.242)' while (True) if output[i].isdigit(): # i has initial value of 15, j=0 f[j]=output[i] j+=1 i+=1 elsif(i == len(output)): break else: i+=1 continue

打印:
>>>f ['1','9','2','1','6','8','4','3','1','1','1','0','0','0']

正如你可以看到我試圖提取IP,因爲它是用點(在此代碼我沒有嘗試提取點,但只有數字), 我無法弄清楚如何得到我想要完全的字符串,因爲它是: F = 192.168.43.111

有什麼建議嗎?更好的命令?

+2

正則表達式是答案:http://stackoverflow.com/questions/10086572/ip-address-validation-in-python-using-regex – zemekeneng

回答

0

對於多對字符串中括號的,我認爲最好是使用正則表達式,像這樣:

import re 

output = '''Scan results for BrainS (192.168.43.111) 
      Scan results for Slave (192.168.43.107) 
      Scan results for SlaveSmall (192.168.43.242)''' 

f = re.findall(r'\(([^()]+)\)',output) 
>>>['192.168.43.111', '192.168.43.107', '192.168.43.242'] 

試試吧here!

+0

哇感謝很多的工作就像一個魅力,怎麼樣,如果有像這樣的幾行?但不同的IP。那麼我會有一些「(」&「)」,有沒有解決方案? – eyal360

+0

編輯您的問題以顯示這些其他行。上述代碼僅適用於字符串中只有一對括號的情況。 – shash678

+0

我剛剛編輯它,我已經添加了我得到的實際輸出,我試圖簡化它之前。我希望這可以幫助你更好地理解我的問題。 – eyal360

0

在這裏,你走了,這個代碼將做的工作!

output = 'My computer IP is = (192.168.43.111) and yours not.' 
ip=[] 
ip_flag = False 

for x in output: 
    if x == '(': 
     ip_flag = True 
     continue 
    if ip_flag: 
     if x != ')': 
      if x != '.': # remove this line of you want the dots 
       ip.append(x) 
     else: 
      break 
print(ip) 
theIp="" 
for i in ip: 
    theIp+=i 
+1

這個答案實際上給了我[[1','9','2',...]形成,我不想在第一名,但效果很好。 – eyal360

+1

@ eyal360如果你想點中刪除此行'如果x =:如果你想有一個字符串只是在端IP地址添加一個循環這樣 'theIp =‘’ 對我' !「」 theIp + = i' done – Amjad

+1

感謝您的幫助,歡呼! – eyal360