電腦版
首頁

搜尋 繁體

6 python 中用 string.maketrans 和 translate 巧妙替換字串

熱門小說推薦

最近更新小說

python 中用 string.maketrans 和 translate 巧妙替換字串

將 nginx 日誌中字串 [2013-07-03T00:29:40-05:00] HTTP 格式化為:"2013-07-03 00:29:40-05:00"

整條日誌如下:

92.82.22.46 - - [2013-07-03T00:29:40-05:00] "GET /images/mask_bg.png HTTP/1.1" 200 195 "/" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)" "-"

將[2013-07-03T00:29:40-05:00] 替換成為:"2013-07-03 00:29:40-05:00"

把 換成"",然後把 T 替換成空格

做法如下:

>>> s='''92.82.22.46 - - [2013-07-03T00:29:40-05:00] "GET /images/mask_bg.png HTTP/1.1" 200 195 "/" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)" "-"'''>>> table = string.maketrans('','""')>>> s.translate(table)'92.82.22.46 - - "2013-07-03T00:29:40-05:00" "GET /images/mask_bg.png HTTP/1.1" 200 195 "/" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)" "-"'>>> s.translate(table).replace('T', ' ',1)#替換掉第一個T為空格'92.82.22.46 - - "2013-07-03 00:29:40-05:00" "GET /images/mask_bg.png HTTP/1.1" 200 195 "/" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)" "-"'也可以這樣:>>> table = re.sub('\[|\]','"',s).replace('T', ' ',1)>>>print table'92.82.22.46 - - "2013-07-03 00:29:40-05:00" "GET /images/mask_bg.png HTTP/1.1" 200 195 "/" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)" "-"'

Loading...

未載入完,嘗試【重新整理網頁】or【關閉小說模式】or【關閉廣告遮蔽】。

使用【Firefox瀏覽器】or【Chrome谷歌瀏覽器】開啟並收藏!

移動流量偶爾打不開,可以切換電信、聯通網路。

收藏網址:www.peakbooks.cc

(>人<;)