python - 将for循环内部和外部的print stmt连接成python中的一个句子

标签 python python-2.7 python-3.x

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/

相关文章:

python - 如何使用 difflib.ndiff 忽略行?

python - 无法部署到 heroku - 没有命名的模块

python - TIC TAC TOE 仅接受整数

python - 检查节点是否存在

python - 基于过滤器的列计算?

python - PyQt5应用程序异常,这是一个错误吗

python:Windows终端中的unicode,使用的编码?

python - pip install pkg 给出权限被拒绝 :/Library/Python/2. 7/site-packages/pkg

python - 如何在不在 Python 中实例化的情况下获取类的类型?

python - 从 SQL 表(Python)中选择数据时如何去掉括号?