Python中字串的處理技巧分享_python

來源:互聯網
上載者:User

一、如何拆分含有多種分隔字元的字串?

實際案例

我們要把某個字串依據分隔字元號拆分不同的字元段,該字串包含多種不同的分隔字元,例如:

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

其中<,>,<;>,<|>,<\t>都是分隔字元,如何處理?

解決方案

連續使用split()方法,每次處理一種分隔字元

# 使用Python2 def mySplit(s,ds): res = [s] for d in ds: t = [] map(lambda x: t.extend(x.split(d)), res) res = t return [x for x in res if x] s = 'asd;aad|dasd|dasd,sdasd|asd,,Adas|sdasd;Asdasd,d|asd' result = mySplit(s, ';,|\t') print(result)
C:\Users\Administrator>C:\Python\Python27\python.exe E:\python-intensive-training\s2.py ['asd', 'aad', 'dasd', 'dasd', 'sdasd', 'asd', 'Adas', 'sdasd', 'Asdasd', 'd', 'asd']

使用Regex的re.split()方法,一次性拆分字串

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

二、如何判斷字串a是否以字串b開頭或結尾?

實際案例

如某目錄有如下檔案:

quicksort.c graph.py heap.java install.sh stack.cpp ......

現在需要給.sh.py結尾的檔案夾上可執行許可權

解決方案

使用字串的startswith()endswith()方法

>>> import os, stat >>> os.listdir('./') ['heap.java', 'quicksort.c', 'stack.cpp', 'install.sh', 'graph.py'] >>> [name for name in os.listdir('./') if name.endswith(('.sh','.py'))] ['install.sh', 'graph.py'] >>> os.chmod('install.sh', os.stat('install.sh').st_mode | stat.S_IXUSR)
[root@iZ28i253je0Z t]# ls -l install.sh -rwxr--r-- 1 root root 0 Sep 15 18:13 install.sh

三、如何調整字串中文本的格式?

實際案例

某軟體的記錄檔,其中日期格式為yyy-mm-dd:

2016-09-15 18:27:26 statu unpacked python3-pip:all 2016-09-15 19:27:26 statu half-configured python3-pip:all 2016-09-15 20:27:26 statu installd python3-pip:all 2016-09-15 21:27:26 configure asdasdasdas:all python3-pip:all

需要把其中日期改為美國日期的格式mm/dd/yyy, 2016-09-15 --> 09/15/2016,要如何處理?

解決方案

使用Regexre.sub()方法做字串替換

利用Regex的擷取的群組,捕獲每個部分內容,在替換字串中各個擷取的群組的順序。

>>> log = '2016-09-15 18:27:26 statu unpacked python3-pip:all' >>> import re # 按順序 >>> re.sub('(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1' , log) '09/15/2016 18:27:26 statu unpacked python3-pip:all' # 使用Regex的分組 >>> re.sub('(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})', r'\g<month>/\g<day>/\g<year>' , log) '09/15/2016 18:27:26 statu unpacked python3-pip:all'

四、如何將多個小字串拼接成一個大的字串?

實際案例

在設計某網路程式時,我們自訂了一個基於UDP的網路通訊協定,按照固定次序向伺服器傳遞一系列參數:

hwDetect: "<0112>" gxDepthBits: "<32>" gxResolution: "<1024x768>" gxRefresh: "<60>" fullAlpha: "<1>" lodDist: "<100.0>" DistCull: "<500.0>"

在程式中我們將各個參數按次序收集到列表中:

["<0112>","<32>","<1024x768>","<60>","<1>","<100.0>","<500.0>"]

最終我們要把各個參數拼接成一個資料包進行發送:

"<0112><32><1024x768><60><1><100.0><500.0>"

解決方案

迭代列表,連續使用'+'操作依次拼接每一個字串

>>> for n in ["<0112>","<32>","<1024x768>","<60>","<1>","<100.0>","<500.0>"]: ... result += n ... >>> result '<0112><32><1024x768><60><1><100.0><500.0>'

使用str.join()方法,更加快速的拼接列表中所有字串

>>> result = ''.join(["<0112>","<32>","<1024x768>","<60>","<1>","<100.0>","<500.0>"]) >>> result '<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'

五、如何對字串進行左, 右, 置中對齊?

實際案例

某個字典中儲存了一系列屬性值:

{ 'ip':'127.0.0.1', 'blog': 'www.anshengme.com', 'title': 'Hello world', 'port': '80' }

在程式中,我們想以以下格式將其內容輸出,如何處理?

ip : 127.0.0.1 blog : www.anshengme.com title : Hello world port : 80

解決方案

使用字串的str.ljust() , str.rjust,str.cente()進行左右置中對齊

>>> info = {'ip':'127.0.0.1','blog': 'www.anshengme.com','title': 'Hello world','port': '80'} # 擷取字典中的keys最大長度 >>> max(map(len, info.keys())) 5 >>> w = max(map(len, info.keys())) >>> for k in info: ... print(k.ljust(w), ':',info[k]) ... # 擷取到的結果 port : 80 blog : www.anshengme.com ip : 127.0.0.1 title : Hello world

使用format()方法,傳遞類似'<20','>20','^20'參數完成同樣任務

>>> for k in info: ... print(format(k,'^'+str(w)), ':',info[k]) ... port : 80 blog : www.anshengme.com ip : 127.0.0.1 title : Hello world

六、如何去掉字串中不需要的字元?

實際案例

過濾掉使用者輸入卡後多餘的空白字元: anshengm.com@gmail.com

過濾某windows下編輯文本中的'\r': hello word\r\n

去掉文本中的unicode組合符號(音調): ‘ní hǎo, chī fàn'

解決方案

字串strip() , lstrip(),rstrip()方法去掉字串兩端字元

>>> email = ' anshengm.com@gmail.com ' >>> email.strip() 'anshengm.com@gmail.com' >>> email.lstrip() 'anshengm.com@gmail.com ' >>> email.rstrip() ' anshengm.com@gmail.com' >>>

刪除某個固定位置的字元,可以使用切片+拼接的方法

>>> s[:3] + s[4:] 'abc123'

字串的replace()方法或Regexre.sub()刪除任意位置字元

>>> s = '\tabc\t123\txyz' >>> s.replace('\t', '') 'abc123xyz'

使用re.sub()刪除多個

>>> import re >>> re.sub('[\t\r]','', string) 'abc123xyzopq'

字串translate()方法,可以同時刪除多種不同字元

>>> import string >>> s = 'abc123xyz' >>> s.translate(string.maketrans('abcxyz','xyzabc')) 'xyz123abc'
>>> s = '\rasd\t23\bAds' >>> s.translate(None, '\r\t\b') 'asd23Ads'
# python2.7 >>> i = u'ní hǎo, chī fàn' >>> i u'ni\u0301 ha\u030co, chi\u0304 fa\u0300n' >>> i.translate(dict.fromkeys([0x0301, 0x030c, 0x0304, 0x0300])) u'ni hao, chi fan'

總結

以上就是為大家整理的Python中字串的處理技巧,文中通過案例、解決方案以及執行個體來示範如何解決,對大家學習或者使用python具有一定的參考借鑒價值。有需要的可以參考借鑒。

更多關於Python相關內容感興趣的讀者可查看本站專題:《Python字串操作技巧匯總》、《Python編碼操作技巧總結》、《Python圖片操作技巧總結》、《Python資料結構與演算法教程》、《Python Socket編程技巧總結》、《Python函數提示總結》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧匯總》

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.