0

this is my code however it keeps outputting the answer as one while I want it to count the characters in the sentence.

#-----------------------------
myList = []
characterCount = 0
#-----------------------------

Sentence = "hello world"
newSentence = Sentence.split(",")
myList.append(newSentence)
print(myList)
for character in myList:
    characterCount += 1
print (characterCount)

thank you for your help

Anastasia
  • 11
  • 1

3 Answers3

0

 The one line solution

len(list("hello world"))  # output 11

or...

 Quick fix to your original code

Revised code:

#-----------------------------
myList = []
characterCount = 0
#-----------------------------

Sentence = "hello world"
myList = list(Sentence)
print(myList)
for character in myList:
    characterCount += 1
print (characterCount)

Output:

['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
11
Community
  • 1
  • 1
Atlas7
  • 2,726
  • 4
  • 27
  • 36
0

You can loop over the sentence and count the characters that way:

#-----------------------------
myList = []
characterCount = 0
#-----------------------------

Sentence = "hello world"

for character in Sentence:
    characterCount += 1

print(characterCount)
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
0

Basically you made a few mistakes: split separator should be ' ' instead of ',', no need to create a new list, and you were looping over words instead of characters.

The code should like the following:

myList = []
characterCount = 0
#-----------------------------

Sentence = "hello world"
newSentence = Sentence.split(" ")

for words in newSentence:
    characterCount += len(words)

print (characterCount)
Mengliu
  • 1
  • 1