标签:方法 sub() 技术 replace open delete 分享图片 www. HERE
(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‘
>>> 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‘
>>> 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,不做映射。第二个参数,指定要替换的字符。
例:
>>> 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) ‘‘
>>> 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)
标签:方法 sub() 技术 replace open delete 分享图片 www. HERE
原文地址:https://www.cnblogs.com/smulngy/p/8879998.html