Python strip lstrip rstrip使用方法

1033 ワード

Pythonのstripは文字列の先頭と末尾の文字を除去するために使用され、同じようにlstripは左の文字を除去するために使用され、rstripは右の文字を除去するために使用されます.
この3つの関数は、除去する先頭と末尾の文字を指定するパラメータを入力します.
入力される文字配列は、コンパイラが両端の対応する文字をすべて除去し、一致する文字がなくなるまで、次のようにします.
theString = 'saaaay yes no yaaaass'
print theString.strip('say')

theStringは、文字が配列内にないまで['s','a','y']配列内の文字を順次除去する.したがって、出力の結果はyes no
簡単でしょう、lstripとrstripの原理は同じです.
注:パラメータが入力されていない場合、デフォルトでは先頭と末尾の空白文字が除去されます.
theString = 'saaaay yes no yaaaass'
print theString.strip('say')
print theString.strip('say ') #say     
print theString.lstrip('say')
print theString.rstrip('say')

実行結果:
yes no es no yes no yaaaass saaaay yes no
注意:パラメータを渡さない場合は、左右の空白文字を削除し、スペースだけでなく改行記号()、水平タブ(t)なども含まれます.
theString = '	
saaaay yes no yaaaass'#
tab , \t print theString.strip()