Python strip()與split()方法

【轉】Python strip()與split()方法

Python strip() 方法用於移除字符串頭尾指定的字符(默認爲空格)。

語法

strip()方法語法:

str.strip([chars]);

參數

chars -- 移除字符串頭尾指定的字符。

返回值

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

實例

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

#!/usr/bin/python

str = 0000000this is string example…wow!!!0000000;
print str.strip( ‘0‘ );

以上實例輸出結果如下:

this is string example…wow!!!

描述

 

Python split()通過指定分隔符對字符串進行切片,如果參數num 有指定值,則僅分隔 num 個子字符串

語法

split()方法語法:

str.split(str="", num=string.count(str)).

參數

  • str – 分隔符,默認爲所有的空字符,包括空格、換行(\n)、製表符(\t)等。
  • num – 分割次數。

返回值

返回分割後的字符串列表。

實例

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

#!/usr/bin/python

str = Line1-abcdef \nLine2-abc \nLine4-abcd;
print str.split( );
print str.split( ', 1 );

以上實例輸出結果如下:

[Line1-abcdef, Line2-abc, Line4-abcd]
[Line1-abcdef, \nLine2-abc \nLine4-abcd]

 


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