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