当前分类:300例题>>正文

Python示例:寻找字符串中的字符的最后一次出现

来源:互联网   更新时间:2023年6月20日  

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 字符串中的任何字符是否等于给定的字符。如果为真,则标志= 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://6yhj.com/leku-p-4361.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 手机APP