[問題] 字串處理 - 簡化程式碼

作者: zha0 (這個帳號是掛網用)   2014-02-24 11:50:08
還是一樣又用 C 的方式在寫程式了 Q_q
輸入的資料
print "\t# {IP} : {PORT} ; {COMMENT}"
print "\tIP:Port1,Port2.....;Comment"
print "\tIP1-IP2:Port1;Comment"
print "\tIP/24:Port1\n"
print "\tIP;Comment"
處理的程式片段
items = '127.0.0.1:443;SSL'
ip = ''
port = ''
ipp = ''
comm = ''
if items.find(';'):
ipp, comm = items.split(';')
if ipp == '':
ipp = options.insert
if ipp.find(':'):
ip, port = ipp.split(':')
if ip == '':
ip = options.insert
print ip, port, comm
請問如何將上面的程式碼, 寫的好看一點, 感覺一直 if 判斷, 好像沒 python 的味道 ~"~
split 可以給了個字元 : ; 然後他就幫你自己切好嗎 ? 好像先從 : 切會比從 ; 切好 ?___?
作者: uranusjr (←這人是超級笨蛋)   2014-02-24 12:14:00
Regular expression我通常不會推薦 re (大多數狀況是 overkill), 不過你這個狀況根本就是 regex 的經典範例 :p
作者: zha0 (這個帳號是掛網用)   2014-02-24 12:16:00
忘了有 RE XDD
作者: WanCW (旺小王)   2014-02-24 12:16:00
if find(_): split(_) 可以換成 .partition(_)[::2]if ipp == '': ipp = _ 可以換成 ipp = ipp or _

Links booklink

Contact Us: admin [ a t ] ucptt.com