i need help understanding how to fix my code (But please no explicit answers, I really need to understand.)
I need to create a program (I'm using IDLE) that will count the number of characters in a given sentence WITHOUT counting spaces.

So far I have:

S = raw_input("Enter Sentence: ")
print "The number of characters in the sentence is %d" % (len(S))

But this does not subtract the spaces. I tried using S.split, but i'm not using it correctly, for instance:

S = raw_input("Enter Sentence: ")
S.strip()
print "The number of characters in the sentence is %d" % (len(S))

thanks for any help/advice

Dani AI

Generated

The behaviour you saw is expected: len() counts everything, and trimming routines only affect leading/trailing whitespace. wanted to ignore spaces inside the sentence, so you need to either remove those spaces before taking the length or explicitly count only the characters you want.

A short, common approach is to remove the space character(s) and then measure:

text = input("Enter sentence: ")
print(len(text.replace(" ", "")))

Note: that removes only the ASCII space (U+0020). Tabs and newlines remain.

If the goal is to ignore all kinds of whitespace (spaces, tabs, newlines), an explicit test per character is clearer and good practice for learning:

text = input("Enter sentence: ")
count = sum(1 for ch in text if not ch.isspace())
print(count)

This uses str.isspace() so it treats tabs and newlines like spaces.

Tie-in to earlier replies: was right that writing the loop yourself is instructive; the generator above is the concise form of that loop. ’s idea of counting spaces and subtracting from the total works for plain spaces, but watch out for other whitespace and for off-by-one mistakes when text contains multiple whitespace characters in a row. For large strings and performance-sensitive code, removing characters with translate (or using a single-pass loop) can be faster than repeated replacements. If still on Python 2, use the appropriate input function for that version.

Recommended Answers

All 2 Replies

Strip only remove spaces from eaither side

You can loop through the string yourself and count each character that isn't a space (recommended if this is homework)(you can loop through strings just like you would loop through a list),

or

you can use S.count(" ") and subtract that from len(S) (NOT recommended for homework).

[code=python]
import string
S = raw_input("Enter Sentence: ")
countSpace=string.count(S," ")
countTotal= len(S)
totalCharacter=countTotal-countSpace
print totalCharacter

you can also try this

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.