找():
在字串中搜尋指定值並傳回找到它的位置。
例如:
txt = "Hello, welcome to my world." x = txt.find("welcome") print(x)
輸出:
7
因此 welcome 依索引位於第七位。如果給出任何其他未定義的單詞,則結果將為 -1。
注意:在上面的例子中,如果使用索引函數而不是find,那麼它將顯示「valueerror:子字串未找到」。如果定義,則輸出將與find函數相同。
循環:
For循環:
例如:1
txt = '1234' for num in txt: print(num,end=' ')
輸出:
1 2 3 4
例如:2
name = input("Enter Name: ") print(name) for alphabet in name: print(alphabet, end='*')
輸出:
Enter Name: guru guru g*u*r*u*
如果:
它根據語句的真假來決定運行程式。
例如:
txt = '12a4' for num in txt: if num>='0' and num<='9': print(num,end=' ') else: print('Not Decimal',end=' ')
輸出:
1 2 Not Decimal 4
在上面的範例中,1,2,4 是十進制,但 a 不是小數,因此在輸出中,根據其他條件,它顯示的不是十進制。
任務:
拉克希米·普里塔
大師 Prasanna
古漢拉賈
瓦拉塔拉揚
找:
1: 以字母「g」開頭的名字
2:名稱以「a」結尾
3:名稱之間有空格
4:名字超過9個字母
name=input("Enter names: ") names=(name).split(",") for letter in names: if letter.startswith('g'): print("Names starts with g are: ",letter) else : letter.endswith('a') print("Names end with a are: ",letter) for space in names: for word in space: if word==' ': print("Names with space: ",space) else: continue for character in names: if len(character)>9: print("Names with more than 9 letters: ",character)
輸出:
Enter names: guru prasanna,guhanraja,lakshmi pritha,varatharajan Names starts with g are: guru prasanna Names starts with g are: guhanraja Names end with a are: lakshmi pritha Names end with a are: varatharajan Names with space: guru prasanna Names with space: lakshmi pritha Names with more than 9 letters: guru prasanna Names with more than 9 letters: lakshmi pritha Names with more than 9 letters: varatharajan
以上是Python Day 字串函數、循環、ifelse 條件與任務的詳細內容。更多資訊請關注PHP中文網其他相關文章!