Python的內置函數(二十九)、 strip()

  • 2019 年 10 月 28 日
  • 筆記

版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

本文鏈接:https://blog.csdn.net/weixin_36670529/article/details/102722210

描述

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

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

語法

strip()方法語法:

str.strip([chars]);

參數

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

返回值

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

實例

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

實例(Python 2.0+)

#!/usr/bin/python    # -*- coding: UTF-8 -*-    str = "00000003210Runoob01230000000";    print str.strip( '0' ); # 去除首尾字元 0    str2 = " Runoob "; # 去除首尾空格    print str2.strip();

以上實例輸出結果如下:

3210Runoob0123 Runoob

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

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

實例

#!/usr/bin/python    # -*- coding: UTF-8 -*-    str = "123abcrunoob321"    print (str.strip( '12' )) # 字元序列為 12

以上實例輸出結果如下:

3abcrunoob3