今天學習語法的時候發現字符串自帶函數find和操作符in功能十分近似,幾乎一模一樣
if
'a'
in
name:
print
'Yes, it contains the string "a"'
if
name.find(
'war'
) !=
-1
:
print
'Yes, it contains the string "war"'
我就想,不可能出現完全一樣功能的函數吧,要不意義何在?果不其然,經查證find()是返回查詢字符串第一個字符在被查詢字符串中第一次出現的位置
舉個栗子:
按照一般理解:abc.find('')返回的要么是0要么是1
abc = "qwertyuiopqwertyuiop"
if abc.find('yui'):#判斷是否包含yui字符串
print("Yes")
else:
print("No")
結果:
一切正常
但如果:
abc = "qwertyuiopqwertyuiop"
if abc.find('abc'):#判斷是否包含yui字符串
print("Yes")
else:
print("No")
你會發現結果還是:
這是因為find()若找不到對應字符串則返回-1
正確的判斷語句應該是:
if abc.find("abc") != -1
...
...
而且find()若找到對應字符串返回的也不是1,那是什么呢? 之前有提到,返回的是查詢字符串在被查詢字符串中第一次出現的位置
舉個栗子:
abc = 'qwertyuiopqwertyuiop'
print(abc.find('yui'))
結果:
打印的是y在字符串‘qwertyuiopqwertyuiop’中第一次出現的位置,注意python從0開始