写一个 Python示例,使用 For 循环和 While 循环计算字符串中的总字符数,并给出一个实例。
这个 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 代码中,我们使用了带有范围的 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 程序对字符进行计数同上。然而,我们只是将 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
标签: VScode