Python 程序查找字符串中的字符的最后一次出现
编写一个 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
字符串中的任何字符是否等于给定的字符。如果为真,则 flag = i
。
接下来,我们使用 If Else 语句检查标志值是否等于 -1 或不等于 0。
string = hello world ch = l flag = -1
- 第一次迭代:对于范围(11)中的 i,如果字符串[i] == char,即
h == l
,条件为假。 - 第二次迭代:如果
e == l
,条件为假,i 为 1。 - 第三次迭代:对于 i = 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
>>>