如何计算python中字符串中的字符数?

how to count characters in a string in python?

我创建了一个函数来计算字符串中的字符数,代码如下:

def count_characters_in_string(mystring):
    s=0
    x=mystring
    for i in x:
        t=i.split()
        s=s+len(t)            
        print("The number of characters in this string is:",s)

count_characters_in_string("Apple")

这就是它 returns: 此字符串中的字符数为:1 此字符串中的字符数为:2 此字符串中的字符数为:3 此字符串中的字符数为:4 这个字符串的字符数是:5

有没有办法只打印最后一行以便打印:

这个字符串的字符数是:5

你可以只使用:

len(mystring)

在您的代码中,要仅打印最后一行,您可以使用:

for i in x:
    s += 1          
print("The number of characters in this string is:",s)

在python中,字符串可以看作是一个列表,你可以只取它的长度

def count_characters_in_string(word):
    return len(word)

使用这个:

def count_characters_in_string(input_string)

    letter_count = 0

    for char in input_string:
        if char.isalpha():
            letter_count += 1

    print("The number of characters in this string is:", letter_count)

当你运行:

count_characters_in_string("Apple Banana")

它会输出:

"The number of characters in this string is: 11"

这应该有效。

def count_characters_in_string(mystring):
    s=0
    x=mystring
    for i in x:
        t=i.split()
        s=s+len(t)            
    print("The number of characters in this string is:",s)

count_characters_in_string("Apple")