Python 程序查找字符串中字符的所有出现位置

编写一个 Python 程序,查找字符串中所有字符的出现位置,并附带实际示例。

Python 程序查找字符串中字符的所有出现位置示例

此 Python 程序允许用户输入一个字符串和一个字符。在此,我们使用 For 循环遍历字符串中的每个字符。在 Python For 循环中,我们使用 If 语句来检查字符串 str1 中的任何字符是否等于字符 ch。如果为真,则将 i 值作为输出打印。请记住,i 是索引位置(从 0 开始)。

str1 = input("Please enter your own String : ")
ch = input("Please enter your own Character : ")

for i in range(len(str1)):
if(str1[i] == ch ):
print(ch, " is Found at Position " , i + 1)

查找字符串中所有字符出现次数的输出。

Please enter your own String : tutorial gateway
Please enter your own Character : t
t  is Found at Position  1
t  is Found at Position  3
t  is Found at Position  12

Python 程序返回字符串中字符的所有出现位置示例 2

此显示字符串中所有字符出现次数的程序与上面的程序相同。但是,我们只是用 While 循环替换了 For 循环,并通过索引迭代字母。

str1 = input("Please enter your own String : ")
ch = input("Please enter your own Character : ")
i = 0

while(i < len(str1)):
if(str1[i] == ch ):
print(ch, " is Found at Position " , i + 1)
i = i + 1

字符串中所有字符出现次数的输出

Please enter your own String : hello world
Please enter your own Character : l
l  is Found at Position  3
l  is Found at Position  4
l  is Found at Position  10

Python 程序显示字符串中字符总出现次数的示例 3

此查找字符串中所有字符出现位置的程序与第一个示例相同。但是,在此 Python 程序中,我们使用了 函数概念来分离 Python 逻辑。

def all_Occurrence(ch, str1):
for i in range(len(str1)):
if(str1[i] == ch ):
print(ch, " is Found at Position " , i + 1)

string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
all_Occurrence(char, string)
Python Program to find All Occurrence of a Character in a String