写一个 Python 程序,用一个实际例子找出字符串中字符的所有出现。
Python 程序查找字符串中的字符的所有出现示例 1
这个 python 程序允许用户输入字符串和字符。这里,我们使用 For 循环来迭代字符串中的每个字符。在 Python For Loop 中,我们使用 If 语句来检查 str1 字符串中的任何字符是否等于字符 ch。如果为真,则我将值打印为输出。记住,I 是一个索引位置(从 0 开始)。
# Python Program to find Occurrence of a Character in a String
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)
Python 字符串输出中字符的所有出现
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
这个 Python 显示字符串程序中字符的所有出现与上面相同。然而,我们只是将循环的替换为循环的。
# Python Program to find Occurrence of a Character in a String
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
Python 中所有字符出现在一个字符串中输出
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 程序中,我们使用了函数的概念来分离 Python 逻辑。
# Python Program to find Occurrence of a Character in a String
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)