首页 > 编程知识 正文

Python 程序:寻找字符串中的字符的第一次出现

时间:2023-11-24 15:33:40 阅读:308879 作者:UBYS

写一个 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)

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。