首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用逗号将单词连接起来,并使用" and“

用逗号将单词连接起来,并使用" and“
EN

Stack Overflow用户
提问于 2017-06-16 02:28:31
回答 7查看 6.4K关注 0票数 23

我正在学习“Automate the Boring Stuff with Python”。我不知道如何从下面的程序中删除最后的输出逗号。这样做的目的是不断提示用户输入值,然后在列表中打印出来,并在末尾插入"and“。输出应如下所示:

代码语言:javascript
复制
apples, bananas, tofu, and cats

我的是这样的:

代码语言:javascript
复制
apples, bananas, tofu, and cats,

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

代码语言:javascript
复制
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()
EN

回答 7

Stack Overflow用户

发布于 2017-06-16 05:48:54

公认的答案是好的,但最好将此功能移到一个单独的函数中,该函数接受一个列表,并处理列表中0、1或2项的边缘情况:

代码语言:javascript
复制
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]

测试用例:

代码语言:javascript
复制
>>> oxfordcomma([])
''
>>> oxfordcomma(['apples'])
'apples'
>>> oxfordcomma(['apples', 'pears'])
'apples and pears'
>>> oxfordcomma(['apples', 'pears', 'grapes'])
'apples, pears, and grapes'
票数 17
EN

Stack Overflow用户

发布于 2017-06-16 02:31:43

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

代码语言:javascript
复制
listed[-1] = listed[-1][:-1]

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

具体实现如下:

代码语言:javascript
复制
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()
票数 8
EN

Stack Overflow用户

发布于 2017-06-16 02:32:59

稍微修改一下你的代码...

代码语言:javascript
复制
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 xxx at the end
lister()
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44574485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档