Python字符串方法詳細介紹2_刪除

# 2.刪減
strip([chars]),
lstrip([chars]),
rstrip([chars])
(1)strip([chars]) strip()函數族用以去除字符串兩端的空白符,保留中間的空白符
空白符由string.whitespace常量定義
>>> print ' abc d '.strip().replace(' ','*')
abc*d

x = '''   line one
    line two
and line three
'''
>>> print x.replace(' ','*')
***line*one
****line*two
and*line*three****
>>> print x.strip().replace(' ','*')
line*one
****line*two
and*line*three
當strip()方法指定輸入參數時,刪除指定的字符,如:
>>> print 'abc'.strip('a')
bc
2)lstrip([chars])和rstrip([chars])分別刪除字符串左端和右端的空白符或指定字符。這兩個方法只會作用於對應端的指定字符(默認作用於空白符)而對應端不管有多少指定字符都會被刪除
>>> print '   abc'.lstrip().replace(' ','*')
abc
>>> print 'abc   '.lstrip().replace(' ','*')
abc***
>>> print 'aabac'.lstrip('a')
bac
>>> print 'abc'.lstrip('c')
abc
>>> print '   abc'.lstrip().replace(' ','*')
abc
>>> print '   abc'.rstrip().replace(' ','*')
***abc
>>> print 'abc'.rstrip('a')
abc
print 'abc'.rstrip('c')
>>> print 'abc'.rstrip('c')
ab


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章