编写一个 Python 程序,通过实际示例查找字符串中字符的第一次出现。
Python程序查找字符串中字符的第一次出现示例
此 Python 程序 允许用户输入 一个字符串和一个字符。
请参阅 字符串 文章,了解有关 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 Loop 中,我们使用 If statement 来检查 str1 字符串中的任何字符是否等于字符 ch。如果为真,则 flag = 1,并执行 Break statement。
string = hello world
ch = l
flag = 0
For Loop 第一次迭代:for i in range(11)
if(string[i] == char)
if(h == l) – 条件为假。
第二次迭代:for 1 in range(11)
if(e == l) – 条件为假。
第三次迭代:for 2 in range(11)
if(str[2] == ch) => if(l == l) – 条件为真。
Flag = 1 并执行 break 语句退出循环。接下来,我们使用 If Else Statement 来检查 flag 值是否等于 0。在这里,条件为假。因此,执行 else 块中的打印语句。
Python程序查找字符串中字符的第一次出现示例 2
此 Python 字符串中字符的第一次出现 程序 与上面的程序相同。但是,我们只是用 While Loop 替换了 For Loop。
# 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 程序 用于查找字符串中字符的第一次出现,与第一个示例相同。但是,这次我们使用了 Functions 概念来分离逻辑。
# 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)
