def make_sandwiches():
ingreds = []
name = input("What is your name for your order? ")
ingreds = input("What do you want for your sandwiches? ")
print("Making " + name.title() + "'s sandwiches... ")
ready = input("Please press 'r' when you're ready. ")
if ready == 'r':
**for ingred in ingreds:**
print("we have put " + ingred.title() + ".")
else:
print("Thanks!")
make_sandwiches()
因此,当我运行此命令并放上"ham, pepper"
时,我会得到类似的东西:
we have put H.
we have put A.
We have put M.
...等等。
如何将其设置为"we have put Ham.", "we have put pepper"
?
答案 0 :(得分:2)
您可以尝试以下操作:
for ingred in ingreds.split():
ingreds
只是一个字符串。对其进行迭代将产生其字符。如果要迭代字符串中的单词(以空格分隔的标记),则必须首先split
。
答案 1 :(得分:0)
要了解发生了什么,您可以尝试:
for i in 'ham':
print(i)
对:
for i in 'ham',:
print(i)
相同的结果:
for i in ['ham']:
print(i)
当'ham'转换为可迭代时,第一个将输出'ham',h,a,m中的字符。第二个和第三个带有的全名是因为,您以第二个元组的形式引入了ham作为可迭代的元素,第二个列出了它。
因此,要解决您的问题,您需要将变量更改为可迭代的。 示例:
'ham, pepper'.split(', ')
结果为:
['ham', 'pepper']
希望有帮助。