0

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

1
  • 2
    Why not just use len("Apple")? Commented Apr 1, 2020 at 8:32

4 Answers 4

3

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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"

1 Comment

You are right, but now it also counts white spaces which it didn't previously
1

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

def count_characters_in_string(word):
    return len(word)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.