这是我的代码,但是当我想让它计算句子中的字符时,它一直将答案作为一个输出。
#-----------------------------
myList = []
characterCount = 0
#-----------------------------
Sentence = "hello world"
newSentence = Sentence.split(",")
myList.append(newSentence)
print(myList)
for character in myList:
characterCount += 1
print (characterCount)谢谢你的帮助
发布于 2017-07-19 00:17:14
使用单行解决方案
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-19 00:17:59
您可以循环遍历句子,并以这种方式计算字符:
#-----------------------------
myList = []
characterCount = 0
#-----------------------------
Sentence = "hello world"
for character in Sentence:
characterCount += 1
print(characterCount)发布于 2017-07-19 05:53:14
基本上你犯了几个错误:拆分分隔符应该是‘’而不是',',不需要创建一个新的列表,并且你是在单词而不是字符上循环。
代码应如下所示:
myList = []
characterCount = 0
#-----------------------------
Sentence = "hello world"
newSentence = Sentence.split(" ")
for words in newSentence:
characterCount += len(words)
print (characterCount)https://stackoverflow.com/questions/45172163
复制相似问题