首页 > 编程知识 正文

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

时间:2023-11-24 15:33:39 阅读:308869 作者:SMMY

写一个 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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。