1. Home
  2. Docs
  3. Python
  4. 字串
  5. 找字串find

找字串find

txt = "/2018/04/23/running-keras-models-on-ios-with-coreml/"
x = txt.find("/20")
print(x) #0

輸出
0

txt = "/2018/04/23/running-keras-models-on-ios-with-coreml/"
x = txt.find("/20")
print(x)
x = txt.find("running")
print(x)
x = txt.find("/")
print(x)
x = txt.find("powenko")
print(x)

輸出
0
12
0
-1

 

text = "John got up. John went to the cinema. John washed his hand."
pos = -1 
while True:
    pos = text.find('John', pos + 1)
    if pos == -1:
        break
    print(text[:pos]) 

print("-----")
pos = -1
while True:
    pos = text.find('John', pos + 1)
    if pos == -1:
        break
    print(text[pos:])     

輸出:
John got up.
John got up. John went to the cinema.
—–
John got up. John went to the cinema. John washed his hand.
John went to the cinema. John washed his hand.
John washed his hand.

sentence = 'abc1 abc2 abc3 abc4 abc5'
 
print(sentence.index('a', 10))
 
print(sentence.index('a', 10, -4))
 
print(sentence.index('a', 7, 18))

輸出

10
10
10