将单词与逗号和“和"连接在一起. [英] Joining words together with a comma, and "and"

查看:142
本文介绍了将单词与逗号和“和"连接在一起.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究'使用Python自动完成无聊的事情".我不知道如何从下面的程序中删除最终的输出逗号.目的是不断提示用户输入值,然后将这些值打印在列表中,并在末尾插入和".输出应如下所示:

I'm working through 'Automate the Boring Stuff with Python'. I can't figure out how to remove the final output comma from the program below. The goal is to keep prompting the user to input values, which are then printed out in a list, with "and" inserted before the end. The output should look something like this:

apples, bananas, tofu, and cats

我的看起来像这样:

apples, bananas, tofu, and cats,

最后一个逗号让我发疯了.

That last comma is driving me NUTS.

def lister():
    listed = []
    while True:
        print('type what you want to be listed or type nothing to exit')
        inputted = input()
        if inputted == '':
            break
        else:
            listed.append(inputted+',')
    listed.insert(-1, 'and')
    for i in listed:
        print(i, end=' ')
lister()

推荐答案

通过将格式设置推迟到打印时间,可以避免在列表中的每个字符串上添加逗号.连接除', '上的最后一项以外的所有项目,然后使用格式插入连接的字符串,最后一个项目与and相连:

You can avoid adding commas to each string in the list by deferring the formatting to print time. Join all the items excluding the last on ', ', then use formatting to insert the joined string with the last item conjuncted by and:

listed.append(inputed)
...
print('{}, and {}'.format(', '.join(listed[:-1]), listed[-1]))


演示:


Demo:

>>> listed = ['a', 'b', 'c', 'd']
>>> print('{}, and {}'.format(', '.join(listed[:-1]), listed[-1]))
a, b, c, and d

这篇关于将单词与逗号和“和"连接在一起.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆