我有一个while循环,它会一直要求用户输入单词,直到他们输入停止。输入存储在名为sentence的变量中。 我的问题是如何将多个输入存储到一个变量中。
我目前的代码是
stop = "stop"
sentence = []
while sentence != stop:
sentence = input("Enter a word: ")
sentence = sentence
print(sentence)
我不明白如何从一个输入中存储变量并打印出以逗号/空格等分隔的所有变量
答案 0 :(得分:1)
stop = "stop"
# okay --- 'sentence' is a list. Good start.
sentence = []
while sentence != stop:
# ...but now you've replaced the list 'sentence' with the word that was just input
# NOTE that in Python versions < 3, you should use raw_input below.
sentence = input("Enter a word: ")
# ...and this does nothing.
sentence = sentence
print(sentence)
如果您执行以下操作,效果会更好:
stop = "stop"
sentence = []
# create a new variable that just contains the most recent word.
word = ''
while word != stop:
word = input("Enter a word: ")
# stick the new word onto the end of the list
sentence.append(word)
print(sentence)
# ...and convert the list of words into a single string, each word
# separated by a space.
print " ".join(sentence)
...或者重新设计一下以省略&#39;停止&#39;,如:
stop = "stop"
sentence = []
while True:
word = input("Enter a word: ")
if word == stop:
# exit the loop
break
sentence.append(word)
# ...and convert the list of words into a single string, each word
# separated by a space.
print " ".join(sentence)
答案 1 :(得分:1)
您需要做的就是将append()
新变量添加到数组中:
>>> a = []
>>> for x in range(5):
... a.append("Hello!")
...
>>> a
['Hello!', 'Hello!', 'Hello!', 'Hello!', 'Hello!']
最后,如果您需要单个变量中的所有内容,则可以使用join()
:
>>> ",".join(a)
'Hello!,Hello!,Hello!,Hello!,Hello!'
答案 2 :(得分:0)
非常简单
stop = "stop"
sentence = []
all = ""
while sentence != stop:
sentence = input("Enter a word: ")
all += sentence + ","
print(all)
答案 3 :(得分:0)
你可能想要这样的东西:
sentence = []
while True:
word = input("Enter a word: ")
if word == "stop":
break
sentence.append(word)
print " ".join(sentence) + "."
答案 4 :(得分:0)
你的一个问题是你经常写你的句子变量。
您要做的是使用list
append
方法。列表上的文档:
https://docs.python.org/3/tutorial/datastructures.html
示例:
a = []
a.append(1)
a.append(2)
a.append(3)
print(a)
[1, 2, 3]
接下来,如果用户输入“停止”,您希望结束代码。所以你应该做的是检查你的循环是否写了“stop”,并使用Python的break
来打破循环。
这意味着您应该将循环更改为无限循环,直到您使用stop
获得while True
。
您的代码现在看起来像这样:
sentence = []
while True:
entry = input("Enter a word: ")
if entry == "stop":
break
sentence.append(entry)
print(sentence)