首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用列表分隔文本?

如何使用列表分隔文本?
EN

Stack Overflow用户
提问于 2017-07-19 00:13:29
回答 3查看 41关注 0票数 0

这是我的代码,但是当我想让它计算句子中的字符时,它一直将答案作为一个输出。

代码语言:javascript
复制
#-----------------------------
myList = []
characterCount = 0
#-----------------------------

Sentence = "hello world"
newSentence = Sentence.split(",")
myList.append(newSentence)
print(myList)
for character in myList:
    characterCount += 1
print (characterCount)

谢谢你的帮助

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-07-19 00:17:14

使用单行解决方案

代码语言:javascript
复制
len(list("hello world"))  # output 11

或者..。

*快速修复您的原始代码

修改后的代码:

代码语言:javascript
复制
#-----------------------------
myList = []
characterCount = 0
#-----------------------------

Sentence = "hello world"
myList = list(Sentence)
print(myList)
for character in myList:
    characterCount += 1
print (characterCount)

输出:

代码语言:javascript
复制
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
11
票数 0
EN

Stack Overflow用户

发布于 2017-07-19 00:17:59

您可以循环遍历句子,并以这种方式计算字符:

代码语言:javascript
复制
#-----------------------------
myList = []
characterCount = 0
#-----------------------------

Sentence = "hello world"

for character in Sentence:
    characterCount += 1

print(characterCount)
票数 0
EN

Stack Overflow用户

发布于 2017-07-19 05:53:14

基本上你犯了几个错误:拆分分隔符应该是‘’而不是',',不需要创建一个新的列表,并且你是在单词而不是字符上循环。

代码应如下所示:

代码语言:javascript
复制
myList = []
characterCount = 0
#-----------------------------

Sentence = "hello world"
newSentence = Sentence.split(" ")

for words in newSentence:
    characterCount += len(words)

print (characterCount)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45172163

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档