編寫一個 Python 程序,通過一個實際例子來查找字符串中的字符的最後一次出現。這個 python 程序允許用戶輸入字符串和字符。
# Python Program to find Last Occurrence of a Character in a String
string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
flag = -1
for i in range(len(string)):
if(string[i] == char):
flag = i
if(flag == -1):
print("Sorry! We haven't found the Search Character in this string ")
else:
print("The Last Occurrence of ", char, " is Found at Position " , flag + 1)
首先,我們使用 For Loop 來迭代一個字符串中的每個字符。其中,我們使用 If 語句來檢查 str1 字符串中的任何字符是否等於給定的字符。如果為真,則標誌= i.
接下來,我們使用 If Else 語句檢查標誌值是否等於-1 或不等於 0。
string = hello world
ch = l
flag =-1
對於循環第一次迭代:對於範圍(11)中的 I,如果(字符串[i] == char)
如果(h = = l)–條件為假。
第二次迭代:如果(e = = l)–條件為假,範圍(11)
中的 1。
第三次迭代:對於範圍(11)中的 2,如果(str[2] == ch) = >如果(l = = l)–條件為真。
標誌= 2
對剩餘的迭代做同樣的事情。這裡,條件(標誌== -1)為假。所以,在執行的 else 塊內打印。
Python 程序查找字符串中的字符的最後一次出現示例 2
這個 Python 上一次出現的一個人物程序和上面一樣。然而,我們只是將 For 循環替換為 While 循環。
# Python Program to find Last Occurrence of a Character in a String
string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
i = 0
flag = -1
while(i < len(string)):
if(string[i] == char):
flag = i
i = i + 1
if(flag == -1):
print("Sorry! We haven't found the Search Character in this string ")
else:
print("The Last Occurrence of ", char, " is Found at Position " , flag + 1)
Python 字符串輸出中的字符的最後一次出現
Please enter your own String : tutorialgateway
Please enter your own Character : t
The Last Occurrence of t is Found at Position 11
Python 程序查找字符串中的最後一次出現示例 3
字符串中的字符的最後一次 Python 出現與第一個示例相同。但是,這一次,我們使用了函數的概念來分離 python 程序的邏輯。
# Python Program to find Last Occurrence of a Character in a String
def last_Occurrence(char, string):
index = -1
for i in range(len(string)):
if(string[i] == char):
index = i
return index
str1 = input("Please enter your own String : ")
ch = input("Please enter your own Character : ")
flag = last_Occurrence(ch, str1)
if(flag == -1):
print("Sorry! We haven't found the Search Character in this string ")
else:
print("The Last Occurrence of ", ch, " is Found at Position " , flag + 1)
Python 字符串輸出中的字符的最後一次出現
Please enter your own String : hello
Please enter your own Character : m
Sorry! We haven't found the Search Character in this string
>>>
Please enter your own String : python programs
Please enter your own Character : p
The Last Occurrence of p is Found at Position 8
>>>
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/247188.html