如何将文本与列表分开?
how do I separate a text with a list?
这是我的代码,但是当我希望它计算句子中的字符数时,它一直将答案输出为一个。
#-----------------------------
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)
这是我的代码,但是当我希望它计算句子中的字符数时,它一直将答案输出为一个。
#-----------------------------
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)