我正在学习“Automate the Boring Stuff with Python”。我不知道如何从下面的程序中删除最后的输出逗号。这样做的目的是不断提示用户输入值,然后在列表中打印出来,并在末尾插入"and“。输出应如下所示:
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()
发布于 2017-06-16 05:48:54
公认的答案是好的,但最好将此功能移到一个单独的函数中,该函数接受一个列表,并处理列表中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'
发布于 2017-06-16 02:31:43
这将删除最后一个单词中的逗号。
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()
发布于 2017-06-16 02:32:59
稍微修改一下你的代码...
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()
https://stackoverflow.com/questions/44574485
复制相似问题