Python3 strip()方法

Python3 字串 Python3 字串


描述

Python strip() 方法用於移除字串頭尾指定的字元(默認為空格)或字元序列。

注意:該方法只能刪除開頭或是結尾的字元,不能刪除中間部分的字元。

語法

strip()方法語法:

str.strip([chars]);

參數

  • chars -- 移除字串頭尾指定的字元序列。

返回值

返回移除字串頭尾指定的字元序列生成的新字串。

實例

以下實例展示了 strip() 函數的使用方法:

實例(Python 3.0+)

#!/usr/bin/python3 str = "*****this is **string** example....wow!!!*****" print (str.strip( '*' )) # 指定字串 *

以上實例輸出結果如下:

this is **string** example....wow!!!

從結果上看,可以注意到中間部分的字元並未刪除。

以上下例演示了只要頭尾包含有指定字元序列中的字元就刪除:

實例(Python 3.0+)

#!/usr/bin/python3 str = "123abczaixian321" print (str.strip( '12' )) # 字元序列為 12

以上實例輸出結果如下:

3abczaixian3

Python3 字串 Python3 字串