python中strip函式的用法

2021-09-28 18:15:29 字數 1418 閱讀 3177

strip()函式原型:string.strip(s[, chars]),它返回的是字串的副本,並刪除前導和字尾字元。

此函式只會刪除頭和尾的字元,中間的不會刪除。

如果strip()的引數為空,那麼會預設刪除字串頭和尾的空白字元(包括\n,\r,\t)。

lstrip():去除左邊

rstrip():去除右邊

去除頭尾空格示例:

>>

>

str=

' ab cd '

>>

>

str' ab cd '

>>

>

str.strip(

)#刪除頭尾空格

'ab cd'

>>

>

str.lstrip(

)#刪除開頭空格

'ab cd '

>>

>

str.rstrip(

)#刪除結尾空格

' ab cd'

去除頭尾數字示例:

>>

> str2 =

'1a2b12c21'

>>

> str2.strip(

'12'

)#刪除頭尾的1和2

'a2b12c'

>>

> str2.lstrip(

'12'

)#刪除開頭的1和2

'a2b12c21'

>>

> str2.rstrip(

'12'

)#刪除結尾的1和2

'1a2b12c'

去除頭尾字母示例:

a=

"aabcacb1111acbba"

print

(a.strip(

"abc"))

print

(a.strip(

"acb"))

print

(a.strip(

"bac"))

print

(a.strip(

"bca"))

print

(a.strip(

"cab"))

print

(a.strip(

"cba"))

輸出:1111

1111

1111

1111

1111

1111

當你傳的引數不管是「abc」還是abc的其他排列形式,這都不重要,

重要的是函式只知道你要刪除的字元是」a」,」b」,」c」。

函式會把你傳的引數拆解成乙個個的字元,然後把頭尾的這些字元去掉!

python中的strip 函式

python 字串 python strip 方法用於移除字串頭尾指定的字元 預設為空格 strip 方法語法 str.strip chars 返回移除字串頭尾指定的字元生成的新字串。以下例項展示了strip 函式的使用方法 usr bin pythonstr 0000000this is stri...

python中strip函式的用法

python中往往使用剝除函式strip 來對使用者的輸入進行清理。strip函式的最一般形式為 str.strip 序列 其中,序列是一段字串,該函式表示從頭或者從尾部開始進行掃瞄,如果掃瞄的字元在序列字串中,則剔除掉,一直到遇到乙個不在序列字串中的字元為止。延伸的函式 str.lstrip 序列...

python中strip函式的用法

python中往往使用剝除函式strip 來對使用者的輸入進行清理。strip函式的最一般形式為 str.strip 序列 其中,序列是一段字串,該函式表示從頭或者從尾部開始進行掃瞄,如果掃瞄的字元在序列字串中,則剔除掉,一直到遇到乙個不在序列字串中的字元為止。延伸的函式 str.lstrip 序列...