这是我的代码,但是当我希望它计算句子中的字符数时,它会一直将答案输出为一个。
#-----------------------------
myList = []
characterCount = 0
#-----------------------------
Sentence = "hello world"
newSentence = Sentence.split(",")
myList.append(newSentence)
print(myList)
for character in myList:
characterCount += 1
print (characterCount)
谢谢你的帮助
单行解决方案
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
您可以遍历句子并按以下方式计算字符数:
#-----------------------------
myList = []
characterCount = 0
#-----------------------------
Sentence = "hello world"
for character in Sentence:
characterCount += 1
print(characterCount)
基本上你犯了一些错误:拆分分隔符应该是''而不是',',不需要创建一个新列表,而且你循环使用单词而不是字符。
代码应如下所示:
myList = []
characterCount = 0
#-----------------------------
Sentence = "hello world"
newSentence = Sentence.split(" ")
for words in newSentence:
characterCount += len(words)
print (characterCount)