python 一些常用字符串處理函數【不斷更新】

看python代碼時遇到的函數,記錄下來供自己查閱

1.rfind()

Str.rfind(substr, beg=0, end=len(str))

參數

  •     str -- 此選項指定要搜索的字符串

  •     beg -- 這是開始索引,默認情況下爲 0

  •   end -- 這是結束索引,默認情況下它等於該字符串的長度

返回值

此方法如果找到返回最後一個索引,否則返回-1

比較find()


  1. filter()函數

    filter()函數是 Python 內置的另一個有用的高階函數,filter()函數接收一個函數 f 和一個list,這個函數 f 的作用是對每個元素進行判斷,返回 TrueFalsefilter()根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新list地址

    e.g

In [50]: def is_odd(x):

    ...: return x % 2 == 1

    ...: filter(is_odd, [1, 4, 6, 7, 9, 12, 17])

    ...: 

Out[50]: <filter at 0x246a5db8c88>

 

In [51]: list(filter(is_odd, [1, 4, 6, 7, 9, 12, 17]))

Out[51]: [1, 7, 9, 17]

 

  1. strip() 方法

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

    e.g.

    str = "0000000     Runoob  0000000";

    print str.strip( '0' );  # 去除首尾字符 0

    str2 = "   Runoob      ";   # 去除首尾空格

    print str2.strip();

    運行結果:

        Runoob  

    Runoob

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