我遇到了这个问题,我应该写一个吃了几个单词的程序(用逗号分隔)并用theese单词吐出一个干净的列表。我无法解决我的问题。有什么想法吗?
def wordlist(word):
return word.split(',')
def main ():
sentence = input("write a few words and seperate them with , ")
splitsentence = wordlist(sentence)
for item in splitsentence:
print(item)
main()
答案 0 :(得分:2)
您每次都打印列表,而不是您正在迭代的特定项目:
而不是print(splitsetnence)
,您需要print(item)
def main():
sentence = input("write a few words and separate them with ,")
splitsentence = wordlist(sentence)
for item in splitsentence:
print (item)
另外,要注意你的缩进。原始帖子中的代码看起来没有正确缩进。
答案 1 :(得分:1)
用raw_input()替换input()。
答案 2 :(得分:1)
您的缩进已关闭,您应该使用raw_input
来获取字符串:
def wordlist(word):
return word.split(',')
def main():
sentence = raw_input("write a few words and seperate them with , ")
splitsentence = wordlist(sentence)
for item in splitsentence:
print(item)
main()
此外,对于这么小的任务,您可以删除wordlist(word)
功能:
def main():
sentence = raw_input("write a few words and seperate them with , ")
splitsentence = wordlist.split(')
for item in splitsentence:
print(item)
main()
答案 3 :(得分:1)
使用raw_input
代替input
,将print(splitsentence)
替换为print(item)
。
请记住,缩进是Python对语句进行分组的方式,例如C或Java使用{
和}
这是我的代码版本:
sentence = raw_input("write a few words and seperate them with , ")
splitsentence = sentence.split(',')
for item in splitsentence:
print item
此代码不需要def main()
或其他行。