日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
判斷字符串是否包含子串,居然有七種方法?

1. 使用 in 和 not

創(chuàng)新互聯(lián)專注于企業(yè)全網(wǎng)整合營銷推廣、網(wǎng)站重做改版、洛浦網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、html5、成都做商城網(wǎng)站、集團(tuán)公司官網(wǎng)建設(shè)、成都外貿(mào)網(wǎng)站建設(shè)公司、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計(jì)等建站業(yè)務(wù),價格優(yōu)惠性價比高,為洛浦等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。

inin 和 not in 在 Python 中是很常用的關(guān)鍵字,我們將它們歸類為 成員運(yùn)算符。

使用這兩個成員運(yùn)算符,可以很讓我們很直觀清晰的判斷一個對象是否在另一個對象中,示例如下:

 
 
 
  1. >>> "llo" in "hello, python" 
  2. True 
  3. >>> 
  4. >>> "lol" in "hello, python" 
  5. False 

2. 使用 find 方法

使用 字符串 對象的 find 方法,如果有找到子串,就可以返回指定子串在字符串中的出現(xiàn)位置,如果沒有找到,就返回 -1

 
 
 
  1. >>> "hello, python".find("llo") != -1 
  2. True 
  3. >>> "hello, python".find("lol") != -1 
  4. False 
  5. >> 

3. 使用 index 方法

字符串對象有一個 index 方法,可以返回指定子串在該字符串中第一次出現(xiàn)的索引,如果沒有找到會拋出異常,因此使用時需要注意捕獲。

 
 
 
  1. def is_in(full_str, sub_str): 
  2.     try: 
  3.         full_str.index(sub_str) 
  4.         return True 
  5.     except ValueError: 
  6.         return False 
  7.  
  8. print(is_in("hello, python", "llo"))  # True 
  9. print(is_in("hello, python", "lol"))  # False 

4. 使用 count 方法

利用和 index 這種曲線救國的思路,同樣我們可以使用 count 的方法來判斷。

只要判斷結(jié)果大于 0 就說明子串存在于字符串中。

 
 
 
  1. def is_in(full_str, sub_str): 
  2.     return full_str.count(sub_str) > 0 
  3.  
  4. print(is_in("hello, python", "llo"))  # True 
  5. print(is_in("hello, python", "lol"))  # False 

5. 通過魔法方法

在第一種方法中,我們使用 in 和 not in 判斷一個子串是否存在于另一個字符中,實(shí)際上當(dāng)你使用 in 和 not in 時,Python 解釋器會先去檢查該對象是否有 __contains__ 魔法方法。

若有就執(zhí)行它,若沒有,Python 就自動會迭代整個序列,只要找到了需要的一項(xiàng)就返回 True 。

示例如下:

 
 
 
  1. >>> "hello, python".__contains__("llo") 
  2. True 
  3. >>> 
  4. >>> "hello, python".__contains__("lol") 
  5. False 
  6. >>> 

這個用法與使用 in 和 not in 沒有區(qū)別,但不排除有人會特意寫成這樣來增加代碼的理解難度。

6. 借助 operator

operator模塊是python中內(nèi)置的操作符函數(shù)接口,它定義了一些算術(shù)和比較內(nèi)置操作的函數(shù)。operator模塊是用c實(shí)現(xiàn)的,所以執(zhí)行速度比 python 代碼快。

在 operator 中有一個方法 contains 可以很方便地判斷子串是否在字符串中。

 
 
 
  1. >>> import operator 
  2. >>> 
  3. >>> operator.contains("hello, python", "llo") 
  4. True 
  5. >>> operator.contains("hello, python", "lol") 
  6. False 
  7. >>>  

7. 使用正則匹配

說到查找功能,那正則絕對可以說是專業(yè)的工具,多復(fù)雜的查找規(guī)則,都能滿足你。

對于判斷字符串是否存在于另一個字符串中的這個需求,使用正則簡直就是大材小用。

 
 
 
  1. import re 
  2.  
  3. def is_in(full_str, sub_str): 
  4.     if re.findall(sub_str, full_str): 
  5.         return True 
  6.     else: 
  7.         return False 
  8.  
  9. print(is_in("hello, python", "llo"))  # True 
  10. print(is_in("hello, python", "lol"))  # False 

【責(zé)任編輯:趙寧寧 TEL:(010)68476606】


分享名稱:判斷字符串是否包含子串,居然有七種方法?
轉(zhuǎn)載來于:http://www.dlmjj.cn/article/dpisoos.html