Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python 進階訓練:七個字串處理的實用解法

字串處理是日常腳本的基本功。以下七個問題都來自真實場景,每題都給出可直接套用的寫法。

一、用多種分隔符拆分字串

待處理的字串同時混用逗號、分號、豎線與 Tab:

s = 'asd;aad|dasd|dasd,sdasd|asd,,Adas|sdasd;Asdasd,d|asd'

連續呼叫 split 逐一處理:

def mySplit(s, ds):
    res = [s]
    for d in ds:
        t = []
        for x in res:
            t.extend(x.split(d))
        res = t
    return [x for x in res if x]      # 過濾空字串

mySplit(s, ';,|\t')

更推薦用正則一次搞定,順便用 + 把連續分隔符合併:

import re
re.split(r'[,;\t|]+', s)
# ['asd', 'aad', 'dasd', 'dasd', 'sdasd', 'asd', 'Adas', 'sdasd', 'Asdasd', 'd', 'asd']

二、判斷開頭或結尾

要為 .sh 與 .py 檔加上可執行權限,別用切片比對,直接用 startswith / endswith,而且它們接受元組:

import os, stat
names = [n for n in os.listdir('./') if n.endswith(('.sh', '.py'))]
os.chmod('install.sh', os.stat('install.sh').st_mode | stat.S_IXUSR)

三、調整字串中的文字格式

把日誌中的 2016-09-15 改成美式 09/15/2016,用 re.sub 搭配捕獲組,重新排列即可:

log = '2016-09-15 18:27:26 statu unpacked python3-pip:all'

re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', log)
# 具名組寫法,可讀性更好
re.sub(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})', r'\g<month>/\g<day>/\g<year>', log)

四、把大量小字串拼成大字串

自訂 UDP 協議要依序把參數拼成封包。用迴圈加 += 會產生大量中間物件,改用 join:

parts = ["<0112>", "<32>", "<1024x768>", "<60>", "<1>", "<100.0>", "<500.0>"]
''.join(parts)
# '<0112><32><1024x768><60><1><100.0><500.0>'

清單中混有數字時,用生成器表達式轉型,避免多建一份清單:

hello = [222, 'sd', 232, '2e', 0.2]
''.join(str(x) for x in hello)      # '222sd2322e0.2'

五、左、右、置中對齊

要把字典內容排成整齊的兩欄,先量出 key 的最大寬度:

info = {'ip': '127.0.0.1', 'blog': 'www.anshengme.com', 'title': 'Hello world', 'port': '80'}
w = max(map(len, info.keys()))

for k in info:
    print(k.ljust(w), ':', info[k])       # rjust 靠右,center 置中

for k in info:
    print(format(k, '^' + str(w)), ':', info[k])   # format 的 < > ^ 對應三種對齊

六、去掉不需要的字元

典型需求:清掉使用者輸入前後的空白、移除 Windows 換行留下的 \r、剝掉 Unicode 組合音符。

email = ' anshengm.com@gmail.com '
email.strip()      # 去兩端;lstrip / rstrip 只去一側

s = '\tabc\t123\txyz'
s.replace('\t', '')                       # 刪除單一字元

import re
re.sub(r'[\t\r]', '', string)             # 一次刪除多種字元

要同時做「替換」與「刪除」,translate 效率最好(Python 2.7 的呼叫方式略有不同):

s = 'abc123xyz'
s.translate(str.maketrans('abcxyz', 'xyzabc'))    # 'xyz123abc'

s = '\rasd\t23\bAds'
s.translate({ord(c): None for c in '\r\t\b'})     # 'asd23Ads'

處理帶音調的拼音字元時,把組合符號的碼位全部對應到 None 即可還原成基本字母:

i = 'n\u0301 ha\u030co, chi\u0304 fa\u0300n'
i.translate(dict.fromkeys(map(ord, '\u0301\u030c\u0304\u0300'), None))   # 'ni hao, chi fan'

選擇原則很簡單:兩端去空白用 strip 系列,固定字元用 replace,多種分隔或複雜規則用正則,大批量映射與刪除用 translate。

Copyright © Linux教程網 All Rights Reserved