寫一個 Python 程序,用一個實際的例子找到字元串中的字元的第一次出現。
python 程序查找字元串中的字元的第一次出現示例 1
這個 python 程序允許用戶輸入字元串和字元。
請參考弦文章了解蟒弦的一切。
# Python Program to check First Occurrence of a Character in a String
string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
flag = 0
for i in range(len(string)):
if(string[i] == char):
flag = 1
break
if(flag == 0):
print("Sorry! We haven't found the Search Character in this string ")
else:
print("The first Occurrence of ", char, " is Found at Position " , i + 1)
Python 字元串輸出中字元的第一次出現
Please enter your own String : hello world
Please enter your own Character : l
The first Occurrence of l is Found at Position 3
這裡,我們使用 For Loop 來迭代字元串中的每個字元。在 For 循環中,我們使用 If 語句來檢查 str1 字元串中的任何字元是否等於字元 ch。如果為真,則標誌= 1,並執行中斷語句。
string = hello world
ch = l
flag = 0
對於循環第一次迭代:對於範圍(11)中的 I,如果(字元串[i] == char)
如果(h = = l)–條件為假。
第二次迭代:如果(e = = l)–條件為假,範圍(11)
中的 1。
第三次迭代:對於範圍(11)中的 2,如果(str[2] == ch) = >如果(l = = l)–條件為真。
標誌= 1,中斷語句退出循環。接下來,我們使用 If Else 語句檢查標誌值是否等於 0。這裡,條件為假。所以,在執行的 else 塊內列印。
Python 程序查找字元串中的字元的第一次出現示例 2
這個 Python 字元的第一次出現程序與上面的相同。然而,我們只是將 For 循環替換為 While 循環。
# Python Program to check First Occurrence of a Character in a String
string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
i = 0
flag = 0
while(i < len(string)):
if(string[i] == char):
flag = 1
break
i = i + 1
if(flag == 0):
print("Sorry! We haven't found the Search Character in this string ")
else:
print("The first Occurrence of ", char, " is Found at Position " , i + 1)
Python 字元串輸出中字元的第一次出現
Please enter your own String : python programming
Please enter your own Character : o
The first Occurrence of o is Found at Position 5
獲取字元串中字元的第一次出現的 Python 程序示例 3
這個 python 程序查找字元串中的字元的第一次出現與第一個例子相同。然而,這一次,我們使用了函數概念來分離邏輯。
# Python Program to check First Occurrence of a Character in a String
def first_Occurrence(char, string):
for i in range(len(string)):
if(string[i] == char):
return i
return -1
str1 = input("Please enter your own String : ")
ch = input("Please enter your own Character : ")
flag = first_Occurrence(ch, str1)
if(flag == -1):
print("Sorry! We haven't found the Search Character in this string ")
else:
print("The first Occurrence of ", ch, " is Found at Position " , flag + 1)
原創文章,作者:WAQ7X,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/129246.html