1、簡單介紹
方法一:字符串strip(),lstrip(),rstrip()方法去掉字符串兩端字符
(1)str.strip() 去除字符串兩端字符
>>> s1 = ' abc 123 ' >>> s1.strip() 'abc 123'
(2)str.lstrip() 去除字符串左端字符
>>> s1.lstrip() 'abc 123 '
(3)str.rstrip() 去除字符串右端字符
>>> s1.rstrip() ' abc 123'
舉例:
>>> s2 = '---aabbcc+++' >>> >>> s2.strip('-+') 'aabbcc'
方法二:刪除單個固定位置的字符,可以使用切片+拼接方式
>>> s = 'abc:123' >>> >>> s[:3]+s[4:] 'abc123'
方法三:使用str.replace()或正則表達式re.sub()刪除任意位置字符串
>>> s = '\tabc\t123\txyz' >>> s.replace('\t','') 'abc123xyz'

>>> help(str.replace) Help on method_descriptor: replace(...) S.replace(old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
字符串的replace()方法只能替換一種字符,如需要替換多種字符,可以使用正則表達式re.sub()方法在《4-3如何調整字符串中文本的格式》中有過介紹。
>>> s = '\tabc\t123\txyz\ropq\r' >>> re.sub('[\t\r]','',s) 'abc123xyzopq'
方法四:使用translate()方法,可以同時刪除多種字符串

>>> help(str.translate) Help on method_descriptor: translate(...) S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256 or None. If the table argument is None, no translation is applied and the operation simply removes the characters in deletechars.
從一個字符映射到另一個字符上去。
第一個參數映射表如果參數為None,不做映射。第二個參數,指定要替換的字符。
例:
1、轉換表是translate的傳統用法。
>>> s = 'abc123xyz'
(1)要把abcxyz分別替換成 opqrst,先要生成轉換表
>>> import string >>> mktrans = string.maketrans('abcxyz','opqrst') >>> mktrans '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`opqdefghijklmnopqrstuvwrst{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
(2)實現轉換
>>> s.translate(mktrans) 'opq123rst'
(3)刪除’abc’其他字符按映射表轉換
>>> s.translate(mktrans,'abc') '123rst'
(4)刪除’abcxyz’其他字符按映射表轉換
>>> s.translate(mktrans,'abcxyz') '123'
(5)全部刪除
>>> s.translate(mktrans,s) ''
2、想要刪除字符串中的某些字符的用法
>>> s.translate(None,'abc') #如果映射表參數為None,那么第二個參數表示要刪除的字符,其余的字符保持不變 '123xyz'
>>> s.translate(None) 'abc123xyz'
例:
>>> s = 'abc\r123\nxyz\t' >>> s 'abc\r123\nxyz\t' >>> s.translate(None,'\r\n\t') 'abc123xyz'
PS:方法四 在py3里translate已經不支持刪除多種字符串了,只保留給字符串重新映射(未做實際驗證,此結論只摘引自http://www.cnblogs.com/laonicc/p/6753915.html)