如何将文本与列表分开?
问题描述:
这是我的代码,但它不断地输出答案作为一个,而我希望它计算在句子中的字符。如何将文本与列表分开?
#-----------------------------
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)
如果你想在句子中的字符数,为什么不使用'LEN(句子)'? – Wondercricket
'sentence.split(“,”)'每次找到该字符时都会尝试查找“,”并分割句子。它没有',',所以它不会分裂它 –