python中index()、find()方法,具體內容如下:
- index() 方法檢測字串中是否包含子字串 str ,該方法與 python find()方法一樣,只不過如果str不在 string中會報一個例外,影響后面程式執行
- index()方法語法:str.index(str, beg=0, end=len(string))
str1='python is on the way']
str2='on'
#空格,等其他運算子對其索引位置也有影響
#在str1中檢測字串中是否含有子字串str2 str1.index(str2,beg=0,end=len(str1))
#如果包含子字串 回傳檢測到的索引值
print(str1.index(str2))
#從索引1開始檢測,檢測長度為3
print(str1.index(str2,1,3))
如果包含子字串回傳開始的索引值,否則拋出例外,
user_name = ['xiaolei','xiaoman','lixia']
pass_word = ['123','456','789']
username = input('username:').strip()
password = input('password:').strip()
if username in user_name and password == pass_word[user_name.index(username)]:
print(f"登錄成功,歡迎您:{username}")
else:
print("錯誤!")
#小編創建了一個Python學習交流群:711312441
若輸入:username == xiaolei
user_name.index(username) == 0
所以:password == pass_word[0] == 123
Python find()方法,不能用于串列list
str.find(str, beg=0, end=len(string))
- str -- 指定檢索的字串
- beg -- 開始索引,默認為0,
- end -- 結束索引,默認為字串的長度,
Python find() 方法檢測字串中是否包含子字串 str ,如果指定 beg(開始) 和 end(結束) 范圍,則檢查是否包含在指定范圍內,如果包含子字串回傳開始的索引值,否則回傳-1,不影響后面程式執行
str1='python is on the way'
str2='on'
str3='nice'
print(str1.index(str2))
#不在字串str1中
print(str1.find(str3))
#從索引1開始檢測,檢測長度為3
print(str1.find(str2,1,3))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/548318.html
標籤:Python