编写一个 Python 程序,通过实际示例计算字符串中字符的出现次数。此 Python 程序允许您输入一个字符串和一个字符。
string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
count = 0
for i in range(len(string)):
if(string[i] == char):
count = count + 1
print("The total Number of Times ", char, " has Occurred = " , count)

在这里,我们使用 For 循环 遍历字符串中的每个字符。在 Python For 循环中,我们使用 If 语句 来检查字符串中的任何字符是否等于给定字符。如果为真,则 count = count + 1。
string = tutorial gateway
ch = t
count = 0
For Loop 第一次迭代:for i in range(11)
if(string[i] == char)
if(t == t) – 条件为真。
count = 0 + 1 => 1
第二次迭代:for 1 in range(11)
if(u == l) – 条件为假。
第三次迭代:for 2 in range(11)
if(string[2] == char) => if(t == t) – 条件为真。
count = 1 + 1 => 2
对剩余的 程序 迭代执行相同操作
使用 While 计算字符串中字符出现次数的 Python 程序
此字符串中字符的总出现次数计数与上面相同。但是,我们将 For 循环替换为了 While 循环。
string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
i = 0
count = 0
while(i < len(string)):
if(string[i] == char):
count = count + 1
i = i + 1
print("The total Number of Times ", char, " has Occurred = " , count)
字符串中字符的总出现次数输出。
Please enter your own String : python programs
Please enter your own Character : p
The total Number of Times p has Occurred = 2
>>>
Please enter your own String : hello
Please enter your own Character : l
The total Number of Times l has Occurred = 2
示例 3:计算字符总出现次数的程序
此给定字符的总出现次数程序与第一个示例相同。但是,这一次,我们使用了 函数 概念来分离逻辑。
def count_Occurrence(ch, str1):
count = 0
for i in range(len(string)):
if(string[i] == char):
count = count + 1
return count
string = input("Please enter your own String : ")
char = input("Please enter your own Character : ")
cnt = count_Occurrence(char, string)
print("The total Number of Times ", char, " has Occurred = " , cnt)
字符串中字符总出现次数的输出
Please enter your own String : Python tutorial
Please enter your own Character : t
The total Number of Times t has Occurred = 3
>>>
Please enter your own String : hi
Please enter your own Character : g
The total Number of Times g has Occurred = 0