Python 用逗号连接单词,以及;及;

Python 用逗号连接单词,以及;及;,python,list,Python,List,我正在通过“”工作。我不知道如何从下面的程序中删除最后的输出逗号。目标是不断提示用户输入值,然后在列表中打印出来,最后插入“and”。输出应如下所示: apples, bananas, tofu, and cats apples, bananas, tofu, and cats, 我的看起来像这样: apples, bananas, tofu, and cats apples, bananas, tofu, and cats, 最后一个逗号快把我逼疯了 def lister():

我正在通过“”工作。我不知道如何从下面的程序中删除最后的输出逗号。目标是不断提示用户输入值,然后在列表中打印出来,最后插入“and”。输出应如下所示:

apples, bananas, tofu, and cats
apples, bananas, tofu, and cats,
我的看起来像这样:

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

这将截断列出的
中最后一个字符串的最后一个字符

许多方法都可以这样做,但这又如何呢

# listed[-1] is the last element of the list
# rstrip removes matching characters from the end of the string
listed[-1] = listed[-1].rstrip(',')
listed.insert(-1, 'and')
for i in listed:
    print(i, end=' ')

您仍将在行尾打印一个空格,但我猜您不会看到它,因此也不会在意。:-)

稍微修改一下代码

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

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

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

演示:


接受的答案是好的,但最好将此功能移动到一个单独的函数中,该函数接受一个列表,并处理列表中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', 'grapes'])
'apples, pears, and grapes'

我会使用f字符串(a,在Python 3.6+中提供):

如果不需要,则可以简化代码并删除
len(words)==2的额外边缘大小写:

def grammatically_join(words):
    if len(words) == 0:
        return ""
    if len(words) == 1:
        return listed[0]
    return f'{", ".join(words[:-1])} and {words[-1]}'

您需要更多信息:OP已在单个字符串中插入逗号。这将在
后面添加一个逗号。改进建议:
str.format
不再推荐,3.6增加了对新的内联格式语法的支持,如果您想使用格式化方法,可以使代码更具可读性:
f“{'、'.join(listed[:-1])}和{listed[-1]}“
。然而,我想说的是,没有格式是最可读的:
,'.join(listed[:-1])+”和“+listed[-1]
@gntskn是
str.format
真的“不再推荐”?我认为格式字符串本身更易于读取,可以提取为
fmt
变量等。我确信
f“…”
字符串有一些用例,特别是在将局部变量粘贴到格式字符串中时,但是说
str.format
是“不再推荐的”看起来有点过分热情了。@ZacCrites你知道吗,你是对的;我想的是
%
接线员。这是我在午夜前通过手机发布的信息:p@gntskn还请注意,在Python版本<3.6中,f字符串不可用。此代码不能处理少于3项的列表。这是否回答了您的问题ion?很好的模块化。对于一般情况,我想我更喜欢传递列表以连接带有
前缀的最后一个项目,因此
join
和其他项目一起添加逗号:
,'.join(列出的[:-1]+[f'和{listed[-1]}]
。但这似乎是一个简单的美学选择。
def grammatically_join(words):
    if len(words) == 0:
        return ""
    if len(words) == 1:
        return listed[0]
    return f'{", ".join(words[:-1])} and {words[-1]}'