成都网站建设设计

将想法与焦点和您一起共享

Python程序:计算字符串中的字符总数

创新互联Python教程:

成都创新互联公司是一家集网站建设,莱州企业网站建设,莱州品牌网站建设,网站定制,莱州网站建设报价,网络营销,网络优化,莱州网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。

写一个 Python 程序,使用 For 循环和 While 循环计算字符串中的总字符数,并给出一个实例。

计算字符串中的字符总数的 Python 程序示例 1

这个 python 程序允许用户输入一个字符串。接下来,它使用 For 循环计算该字符串中的字符总数。

这里,我们使用 Python For 循环来迭代字符串中的每个字符。在 For 循环中,我们递增每个字符的总值。

# Python Program to Count Total Characters in a String

str1 = input("Please Enter your Own String : ")
total = 0

for i in str1:
    total = total + 1

print("Total Number of Characters in this String = ", total)

Python 程序计算字符串中的字符数示例 2

这个字符串字符程序和上面的例子一样。然而,在这个 Python 代码中,我们使用了带有范围的 For Loop 。

# Python Program to Count Total Characters in a String

str1 = input("Please Enter your Own String : ")
total = 0

for i in range(len(str1)):
    total = total + 1

print("Total Number of Characters in this String = ", total)

Python 计数字符串输出

Please Enter your Own String : Tutorial Gateway
Total Number of Characters in this String =  16
>>> 
Please Enter your Own String : Python
Total Number of Characters in this String =  6

计算字符串中的字符数的 Python 程序示例 3

这个 python 程序对字符进行计数同上。然而,我们只是将 For 循环替换为 While 循环。

# Python Program to Count Total Characters in a String

str1 = input("Please Enter your Own String : ")
total = 0
i = 0

while(i < len(str1)):
    total = total + 1
    i = i + 1

print("Total Number of Characters in this String = ", total)
Please Enter your Own String : Python Programming
Total Number of Characters in this String =  18

本文题目:Python程序:计算字符串中的字符总数
链接地址:https://chengdu.cdxwcx.cn/article/ccdshis.html