编写一个 Python 程序,通过实际示例查找字符串中字符的最后出现位置。此 Python 程序允许用户输入字符串和字符。
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 statement 检查 str1 字符串中的任何字符是否等于给定字符。如果为真,则 flag = i。
接下来,我们使用 If Else Statement 检查 flag 值是否等于 -1 或不等于 0。
string = hello world
ch = l
flag = -1
For Loop 第一次迭代:for i in range(11)
if(string[i] == char)
if(h == l) – 条件为 false。
第二次迭代:for 1 in range(11)
if(e == l) – 条件为 false。
第三次迭代:for 2 in range(11)
if(str[2] == ch) => if(l == l) – 条件为 True。
flag = 2
对剩余的迭代执行相同操作。这里,条件(flag == -1)为 False。因此,else 块内的打印被执行。
Python 程序查找字符串示例 2 中字符的最后出现位置
此 Python 字符最后出现程序与上述相同。但是,我们只是将 For Loop 替换为 While Loop。
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)
字符串中字符的最后出现输出
Please enter your own String : tutorialgateway
Please enter your own Character : t
The Last Occurrence of t is Found at Position 11
Python 程序查找字符串示例 3 中字符的最后出现位置
字符串中字符的最后出现与第一个示例相同。但是,这次我们使用了 Functions 概念来分离 Python 程序逻辑。
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)
字符串中字符的最后出现输出
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
>>>