欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2016年09月17日 10:01:06   投稿:daisy  
這篇文章給大家分享了Python中字符串的處理技巧,包括拆分含有多種分隔符的字符串、判斷字符串a(chǎn)是否以字符串b開(kāi)頭或結(jié)尾、調(diào)整字符串中文本的格式已經(jīng)將多個(gè)小字符串拼接成一個(gè)大的字符串等,感興趣的朋友們可以通過(guò)閱讀下文來(lái)學(xué)習(xí)。

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

實(shí)際案例

我們要把某個(gè)字符串依據(jù)分隔符號(hào)拆分不同的字符段,該字符串包含多種不同的分隔符,例如:

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

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

解決方案

連續(xù)使用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']

使用正則表達(dá)式的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(chǎn)是否以字符串b開(kāi)頭或結(jié)尾?

實(shí)際案例

如某目錄有如下文件:

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

現(xiàn)在需要給.sh.py結(jié)尾的文件夾上可執(zhí)行權(quán)限

解決方案

使用字符串的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

三、如何調(diào)整字符串中文本的格式?

實(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

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

解決方案

使用正則表達(dá)式re.sub()方法做字符串替換

利用正則表達(dá)式的捕獲組,捕獲每個(gè)部分內(nèi)容,在替換字符串中各個(gè)捕獲組的順序。

>>> 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' # 使用正則表達(dá)式的分組 >>> 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'

四、如何將多個(gè)小字符串拼接成一個(gè)大的字符串?

實(shí)際案例

在設(shè)計(jì)某網(wǎng)絡(luò)程序時(shí),我們自定義了一個(gè)基于UDP的網(wǎng)絡(luò)協(xié)議,按照固定次序向服務(wù)器傳遞一系列參數(shù):

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

在程序中我們將各個(gè)參數(shù)按次序收集到列表中:

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

最終我們要把各個(gè)參數(shù)拼接成一個(gè)數(shù)據(jù)包進(jìn)行發(fā)送:

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

解決方案

迭代列表,連續(xù)使用'+'操作依次拼接每一個(gè)字符串

>>> 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>'

如果列表中有數(shù)字,可以使用生成器進(jìn)行轉(zhuǎn)換:

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

五、如何對(duì)字符串進(jìn)行左, 右, 居中對(duì)齊?

實(shí)際案例

某個(gè)字典中存儲(chǔ)了一系列屬性值:

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

在程序中,我們想以以下格式將其內(nèi)容輸出,如何處理?

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

解決方案

使用字符串的str.ljust() , str.rjust,str.cente()進(jìn)行左右居中對(duì)齊

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

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

>>> 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

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

實(shí)際案例

過(guò)濾掉用戶輸入卡后多余的空白字符: anshengm.com@gmail.com

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

去掉文本中的unicode組合符號(hào)(音調(diào)): ‘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' >>>

刪除某個(gè)固定位置的字符,可以使用切片+拼接的方法

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

字符串的replace()方法或正則表達(dá)式re.sub()刪除任意位置字符

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

使用re.sub()刪除多個(gè)

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

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

>>> 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'

總結(jié)

以上就是為大家整理的Python中字符串的處理技巧,文中通過(guò)案例、解決方案以及實(shí)例來(lái)演示如何解決,對(duì)大家學(xué)習(xí)或者使用python具有一定的參考借鑒價(jià)值。有需要的可以參考借鑒。

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Python字符串操作技巧匯總》、《Python編碼操作技巧總結(jié)》、《Python圖片操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python入門(mén)與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

相關(guān)文章

  • 關(guān)于Python的一些學(xué)習(xí)總結(jié)

    關(guān)于Python的一些學(xué)習(xí)總結(jié)

    這篇文章主要介紹了關(guān)于Python的一些總結(jié),希望自己以后在學(xué)習(xí)Python的過(guò)程中可以邊學(xué)習(xí)邊總結(jié),就自己之前的學(xué)習(xí)先做以總結(jié),之后將不斷總結(jié)更新
    2018-05-05
  • Python Django請(qǐng)求和響應(yīng)對(duì)象詳解

    Python Django請(qǐng)求和響應(yīng)對(duì)象詳解

    這篇文章主要給大家介紹了關(guān)于django的請(qǐng)求和響應(yīng)對(duì)象,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用django具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-11-11
  • 使用python pyserial模塊串口通信方式

    使用python pyserial模塊串口通信方式

    這篇文章主要介紹了使用python pyserial模塊串口通信方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • python?中的np.zeros()和np.ones()函數(shù)詳解

    python?中的np.zeros()和np.ones()函數(shù)詳解

    這篇文章主要介紹了python?中的np.zeros()和np.ones()函數(shù),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-04-04
  • Python GUI編程學(xué)習(xí)筆記之tkinter界面布局顯示詳解

    Python GUI編程學(xué)習(xí)筆記之tkinter界面布局顯示詳解

    這篇文章主要介紹了Python GUI編程學(xué)習(xí)筆記之tkinter界面布局顯示,結(jié)合實(shí)例形式分析了Python GUI編程中tkinter界面布局顯示的相關(guān)操作技巧與使用注意事項(xiàng),需要的朋友可以參考下
    2020-03-03
  • 基于python實(shí)現(xiàn)藍(lán)牙通信代碼實(shí)例

    基于python實(shí)現(xiàn)藍(lán)牙通信代碼實(shí)例

    這篇文章主要介紹了基于python實(shí)現(xiàn)藍(lán)牙通信代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • Python專(zhuān)用方法與迭代機(jī)制實(shí)例分析

    Python專(zhuān)用方法與迭代機(jī)制實(shí)例分析

    這篇文章主要介紹了Python專(zhuān)用方法與迭代機(jī)制,包括類(lèi)的私有方法、專(zhuān)有方法、模塊私有對(duì)象、迭代__iter__()方法的對(duì)象等,需要的朋友可以參考下
    2014-09-09
  • 淺談selenium如何應(yīng)對(duì)網(wǎng)頁(yè)內(nèi)容需要鼠標(biāo)滾動(dòng)加載的問(wèn)題

    淺談selenium如何應(yīng)對(duì)網(wǎng)頁(yè)內(nèi)容需要鼠標(biāo)滾動(dòng)加載的問(wèn)題

    這篇文章主要介紹了淺談selenium如何應(yīng)對(duì)網(wǎng)頁(yè)內(nèi)容需要鼠標(biāo)滾動(dòng)加載的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-03-03
  • Python3.7安裝keras和TensorFlow的教程圖解

    Python3.7安裝keras和TensorFlow的教程圖解

    這篇文章主要介紹了Python3.7安裝keras和TensorFlow經(jīng)驗(yàn),本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-10-10
  • python 輪詢(xún)執(zhí)行某函數(shù)的2種方式

    python 輪詢(xún)執(zhí)行某函數(shù)的2種方式

    這篇文章主要介紹了python 輪詢(xún)執(zhí)行某函數(shù)的2種方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-05-05

最新評(píng)論