2017-07-18 160 views
0

這是我的代碼,但它不斷地輸出答案作爲一個,而我希望它計算在句子中的字符。如何將文本與列表分開?

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

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

感謝你的幫助

+1

如果你想在句子中的字符數,爲什麼不使用'LEN(句子)'? – Wondercricket

+0

'sentence.split(「,」)'每次找到該字符時都會嘗試查找「,」並分割句子。它沒有',',所以它不會分裂它 –

回答

0

的一個在線解決方案

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

或...

快速修復到原來的代碼

修改後的代碼:

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

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

輸出:

['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] 
11 
0

您可以遍歷所有的句子和計數的字符方式:

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

Sentence = "hello world" 

for character in Sentence: 
    characterCount += 1 

print(characterCount) 
0

基本上你犯了一些錯誤:拆分分離器應該是「」,而不是」 ',不需要創建一個新的列表,而是循環使用單詞而不是字符。

的代碼應該像下面這樣:

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

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

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

print (characterCount) 
相關問題