如何判斷字符串A在字符串B中?
1. 使用 in 關鍵字
s = 'I love python' print('love' in s) # 結果為True print('byebye' in s) # 結果為False
2. 使用 __contains__()魔法方法,in關鍵字底層調用的就是此方法
s = 'I love python' print(s.__contains__('love')) # 結果為True print(s.__contains__('byebye')) # 結果為False
3. 使用字符串的find方法,從左到右開始查找,如果字符串A存在於字符串B中,就返回查找到的第一個字符在B中的索引值,如果想從右向左查找,可以使用rfind方法。如果不存在,那么返回-1,也可指定開始索引和結束索引
s = 'I love python' print(s.find('love')) # 返回2 print(s.find('byebye')) # 返回-1
4. 使用字符串的index方法,從左到右開始查找,如果字符串A存在於字符串B中,就返回查找到的第一個字符在B中的索引值,如果想從右向左查找,可以使用rindex方法。如果不存在,那么就報錯,也可指定開始索引和結束索引
s = 'I love python' print(s.index('love')) # 返回2 print(s.index('byebye')) # 報錯 ValueError: substring not found