def PrintFruiteListSentence(list_of_fruits):
print 'You would like to eat',
for i, item in enumerate (list_of_fruits):
if i != (len(list_of_fruits) - 1):
print item, 'as fruit', i+2, 'and',
else:
print item, 'as fruit', i+2,
print 'in your diet'
o/p 您希望在饮食中吃苹果作为水果 1,橙子作为水果 2,香蕉作为水果 3,葡萄作为水果 4。
如何将这句话放入变量中,并将其传递给另一个函数??? 我想将这句话作为输入传递给另一个函数。
最佳答案
只需将对 print
的调用更改为连接到实际字符串即可。
def PrintFruiteListSentence(list_of_fruits):
sentence = 'You would like to eat '
for i, item in enumerate (list_of_fruits):
if i != (len(list_of_fruits) - 1):
sentence += item + ' as fruit ' + str(i+2) + ' and '
else:
sentence += item + ' as fruit ' + str(i+2)
sentence += ' in your diet'
print sentence
您还可以使用列表理解代替 for 循环,但这只是不必要的:
另请注意,如果您希望 i
从特定数字开始,您可以将索引传递给 enumerate
>>> def PrintFruiteListSentence(list_of_fruits):
sentence = 'You would like to eat ' + ' and '.join(fruit + ' as fruit ' + str(index) for index,fruit in enumerate(list_of_fruits,1)) + ' in your diet'
print(sentence)
>>> PrintFruiteListSentence(['apple','orange','grapes'])
You would like to eat apple as fruit 1 and orange as fruit 2 and grapes as fruit 3 in your diet
编辑:确保将 i+2
转换为 str(i+2)
关于python - 将for循环内部和外部的print stmt连接成python中的一个句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33789601/