Php接单平台:用逗号和“and”连接单词(a joining word)

我正在通过 'Automate the Boring Stuff with Python' 工作。我无法弄清楚如何从的程序中删除最终输出逗号。目标是不断提示用户输入值,然后将其打印在列表中,并在末尾之前插入“和”。输出应该是这样的:

apples, bananas, tofu, and cats

我的看起来像这样:

apples, bananas, tofu, and cats,

最后一个逗号快把我逼疯了。

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()
46

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

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

演示:

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

接受的答案是好的,但它可能是更好地将此功能移动到一个单独的功能,需要一个列表,并处理边缘情况的 0,1,或 2 项在列表中:

def oxfordcomma(listed):
    if len(listed) == 0:
        return ''
    if len(listed) == 1:
        return listed[0]
    if len(listed) == 2:
        return listed[0] + ' and ' + listed[1]
    return ', '.join(listed[:-1]) + ', and ' + listed[-1]

测试用例:

>>> oxfordcomma([])
''
>>> oxfordcomma(['apples'])
'apples'
>>> oxfordcomma(['apples', 'pears'])
'apples and pears'
>>> oxfordcomma(['apples', 'pears', 'gs'])
'apples, pears, and gs'
8

这将删除最后一个单词中的逗号。

listed[-1] = listed[-1][:-1]

它的工作方式是listed[-1]从列表中获取最后一个值,我们使用=将该值分配给listed[-1][:-1],这是列表中最后一个单词的切片,最后一个字符之前的所有内容。

实现如下所示:

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')
    listed[-1] = listed[-1][:-1]
    for i in listed:
        print(i, end=' ')
lister()
4

修改你的代码一点点...

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) # removed the comma here
    print(', '.join(listed[:-2]) + ' and ' + listed[-1])  #using the join operator, and appending and  at the end
lister()

本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处

(833)
Cd纹怎么编程:鱼尾纹中的一对多关系看起来怎么样
上一篇
Cl摩尔质量:使用 MATLAB查找摩尔质量
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(44条)