Python字符串處理實例詳解
一、拆分含有多種分隔符的字符串
1.如何拆分含有多種分隔符的字符串
問題: 我們要把某個字符串依據分隔符號拆分不同的字段,該字符串包含多種不同的分隔符,例如:
s = "ab;cd|efg|hi,jkl|mn/topq;rst,uvw/txyz"
其中;,|,/t 都是分隔符號,如何處理?
方法一: 連續使用str.split()方法,每次處理一種分隔符號
s = "ab;cd|efg|hi,jkl|mn/topq;rst,uvw/txyz"def mySplit(s,ds): res = [s] for d in ds: t = [] map(lambda x: t.extend(x.split(d)), res) res = t return resprint mySplit(s,';|,/t')輸出:['ab', 'cd', 'efg', 'hi', 'jkl', 'mn', 'opq', 'rst', 'uvw', 'xyz']
方法二: 使用正則表達式的re.split()方法,一次性拆分字符串
import res = "ab;cd|efg|hi,jkl|mn/topq;rst,uvw/txyz"print re.split(r'[;|,/t]+',s)輸出:['ab', 'cd', 'efg', 'hi', 'jkl', 'mn', 'opq', 'rst', 'uvw', 'xyz']
二、調整字符串中文本格式
1. 如何判斷字符串a是否以字符串b開頭或結尾
問題:某文件系統目錄下有一系列文件:a.py,quicksort.c,stack.cpp,b.sh , 編寫程序給其中所有.sh文件和.py文件加上用戶可執行權限?
解決方案: 使用字符串中的str.startswith()和end.startswith()方法 (注意:多個匹配時參數使用元組)
In [1]: import os# 列出當前目錄以.sh和以.py結尾的文件In [2]: [name for name in os.listdir('.') if name.endswith(('.py','.sh'))]Out[2]: ['b.sh', 'a.py']In [3]: import stat# 查看 a.py 文件權限In [4]: os.stat('a.py').st_modeOut[4]: 33204# 把文件權限轉換成8進制,即為平常看到的權限In [5]: oct(os.stat('a.py').st_mode)Out[5]: '0100664'# 更改文件權限,添加一個可執行權限In [6]: os.chmod('a.py',os.stat('a.py').st_mode | stat.S_IXUSR)In [7]: lltotal 0-rwxrw-r-- 1 yangyang 0 5月 9 14:48 a.py*-rw-rw-r-- 1 yangyang 0 5月 9 14:48 b.sh-rw-rw-r-- 1 yangyang 0 5月 9 14:48 quicksort.c-rw-rw-r-- 1 yangyang 0 5月 9 14:48 stack.cpp2.如何對字符串中文本的格式進行調整
問題: 某軟件的log文件,其中日期格式為“yyyy-mm-dd”:
2017-05-08 09:12:48 status half-configured passwd:amd64 1:4.2-3.1ubuntu5.22017-05-08 09:12:48 status installed passwd:amd64 1:4.2-3.1ubuntu5.22017-05-08 09:12:48 status unpacked passwd:amd64 1:4.2-3.1ubuntu5.22017-05-08 09:12:48 status unpacked passwd:amd64 1:4.2-3.1ubuntu5.22017-05-08 09:12:48 status half-configured passwd:amd64 1:4.2-3.1ubuntu5.22017-05-08 09:12:48 status installed passwd:amd64 1:4.2-3.1ubuntu5.22017-05-08 09:12:48 startup packages configure09:12:48 startup packages configure
我們想把其中日期改為美國日期的格式"mm/dd/yyyy",2017-05-08 ==> 05/08/2017 ,應如何處理?
解決方案:使用正則表達式re.sub()方法做字符串替換,利用正則表達式的捕獲組捕獲每個部分內容,在字符串中調整各個組的捕獲順序。
| 
 
 | 
新聞熱點
疑難解答