天天看點

python筆記07: str内置函數str内置函數

str内置函數

  • 字元串查找類
  • find: 查找字元串中是否包含一個子串 傳回第一次發現這個字元串的位置
  • index: index如果找不到會報錯
  • rfind, lfind: 從左查找或者從右查找
# help(str)
# help(str.find)
           
s1 = "so we beat on,boats against the current."
s3 = "borne back ceaselessly into the past."
s2 = "current"
           
32
           
32
           
-1
           
# 子字元串不在母字元串時,index會報錯或引發異常
s1.index(s3)
           
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-24-f70fe0294a29> in <module>()
      1 # 子字元串不在母字元串時,index會報錯或引發異常
----> 2 s1.index(s3)


ValueError: substring not found
           
# 使用時還可以使用區間
s1 = "maluyuan maluyuan maluyuan"
s2 = "maluyuan"
# 從第九個字元開始找
s1.find(s2,9)
           
9
           
18
           

判斷類函數

  • 此類函數特點是一般用is開頭,比如islower
  • isalpha 判斷是否是字母
    • 此函數的前提是字元串至少包含一個字元,如果沒有傳回false
    • 漢字被認為是alpha,是以此函數不能作為區分中英文的辨別,區分中英文請使用unicode碼