0

这是我的代码,但是它一直将答案输出为一个,而我希望它计算句子中的字符。

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

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

谢谢您的帮助

4

3 回答 3

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
于 2017-07-18T16:17:14.347 回答
0

您可以循环遍历句子并以这种方式计算字符:

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

Sentence = "hello world"

for character in Sentence:
    characterCount += 1

print(characterCount)
于 2017-07-18T16:17:59.377 回答
0

基本上你犯了一些错误:分割分隔符应该是''而不是',',不需要创建一个新列表,你循环的是单词而不是字符。

代码应如下所示:

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

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

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

print (characterCount)
于 2017-07-18T21:53:14.177 回答