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

编写一个 Python 程序,使用 For 循环和 While 循环以及实际示例来计算字符串中的总字符数。

使用 for 循环计算字符串中的总字符数

此程序允许用户输入一个字符串。然后,它使用 For 循环计算此字符串中的总字符数。

在这里,我们使用 Python For 循环遍历字符串中的每个字符。在 For 循环中,我们为每个字符递增总数。

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 Program to Count Total Characters in a String

使用 for 循环 range 函数

字符串 字符程序与上面的示例相同。但是,在此 Python 代码中,我们使用带有 For 循环Range

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)

计算字符串字符的输出

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

Python 程序使用 while 循环计算字符串中的字符数

程序 计算字符数与上面相同。但是,我们用 While 循环 替换了 For 循环。

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

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

print("Total Number of Characters = ", total)
Please Enter your Own Text : Hello World
Total Number of Characters =  11

Python 程序使用函数计算字符串中的字符数

def totalChars(txt):
    count = 0
    for i in txt:
        count += 1
    return count

txt = input("Enter a Text = ")

print("Total = ", totalChars(txt))
Enter a Text = hello world!
Total =  12

使用递归

def totalChars(txt):
    if txt == '':
        return 0
    else:
        return 1 + totalChars(txt[1:])

txt = input("Enter a Text = ")

print("Total = ", totalChars(txt))
Enter a Text = Good Day for all of you
Total =  23

使用 len 和 sum 函数计算字符串中的字符数

此编程语言有一个内置的字符串函数 len() 来获取字符串长度。

txt = input("Enter a Text = ")

count = len(txt)

print("Total = ", count)
Enter a Text = welcome
Total =  7

使用列表推导式

列表推导将字符串转换为列表,然后使用列表 len 函数查找总项数。

txt = input("Enter a Text = ")

count = len([char for char in txt])

print("Total = ", count)
Enter a Text = Jhon Wick
Total =  9

使用 sum() 函数

txt = input("Enter a Text = ")

count = sum(1 for char in txt)

print("Total = ", count)
Enter a Text = Jhony Williams
Total =  14

使用 lambda 和 map 函数

txt = input("Enter a Text = ")

tot = sum(map(lambda char: 1, txt))

print("Total = ", tot)
Enter a Text = New York
Total =  8