Python程序:计算字符串中的字符出现次数

创新互联Python教程:

创新互联公司专注于宜良企业网站建设,自适应网站建设,商城网站开发。宜良网站建设公司,为宜良等地区提供建站服务。全流程按需定制开发,专业设计,全程项目跟踪,创新互联公司专业和态度为您提供的服务

写一个 Python 程序来计算字符串中的字符的出现次数,并给出一个实例。这个 python 程序允许您输入字符串和字符。

# Python Program to Count Occurrence of a Character in a String

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 Loop 来迭代一个字符串中的每个字符。在 Python For Loop 中,我们使用 If 语句来检查字符串中的任何字符是否等于给定的字符。如果为真,则计数=计数+ 1。

字符串=教程网关 ch = t 计数= 0

对于循环第一次迭代:对于范围(11)中的 I,如果(字符串[i] == char) 如果(t = = t)–条件为真。 计数= 0 + 1 = > 1

第二次迭代:如果(u = = l)–条件为假,范围(11) 中的 1。

第三次迭代:对于范围(11)中的 2,如果(字符串[2] == char) = >如果(t = = t)–条件为真。 计数= 1 + 1 = > 2

对剩余的程序迭代进行同样的操作

计算字符出现次数的 Python 程序示例 2

这个 Python 计算字符串程序中一个字符的总出现次数与上面相同。然而,我们只是将 For 循环替换为 While 循环。

# Python Program to Count Occurrence of a Character in a String

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)

字符串输出中 python 字符的出现

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

计算字符总出现次数的 Python 程序示例 3

给定字符程序的 Python 总出现次数与第一个示例相同。但是,这一次,我们使用了函数的概念来分离逻辑。

# Python Program to Count Occurrence of a Character in a String

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)

字符串输出中 python 字符的出现

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

网页标题:Python程序:计算字符串中的字符出现次数
分享链接:http://www.shufengxianlan.com/qtweb/news11/75761.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联