Clem-Clem123
Clem-Clem123

Reputation: 57

how to count characters in a string in python?

I created a function that would count the number of characters in a string with this code:

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")

This is what it returns: The number of characters in this string is: 1 The number of characters in this string is: 2 The number of characters in this string is: 3 The number of characters in this string is: 4 The number of characters in this string is: 5

Is there a way to only print the last line so that it prints:

The number of characters in this string is: 5

Upvotes: 0

Views: 26046

Answers (4)

Caleb Mackle
Caleb Mackle

Reputation: 140

Use this:

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)

When you run:

count_characters_in_string("Apple Banana")

It'll output:

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

Upvotes: 2

Salman Baqri
Salman Baqri

Reputation: 109

This should work.

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")

Upvotes: 0

kederrac
kederrac

Reputation: 17322

you can just use:

len(mystring)

in your code, to print only the last line you can use:

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

Upvotes: 3

K.Doruk
K.Doruk

Reputation: 106

In python string can be seen as a list u can just take its lenght

def count_characters_in_string(word):
    return len(word)

Upvotes: 1

Related Questions