how do I separate a text with a list?

59 Views Asked by At

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

3

There are 3 best solutions below

0
On BEST ANSWER

 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
0
On

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)
0
On

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)