python - 我需要在列表中使用的 .join() 方法不适用于该列表中的最后两个值
问题描述
我正在解决 Automate The Boring Stuff In Python 中的练习项目,我目前在第 4 章。练习希望我将列表的内容变成字符串,并为倒数第二个值添加一个额外的值。
这是问题:
For practice, write programs to do the following tasks.
Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns
a string with all the items separated by a comma and a space, with and
inserted before the last item. For example, passing the previous spam list to
the function would return 'apples, bananas, tofu, and cats'. But your func-
tion should be able to work with any list value passed to it.
到目前为止,我已经在一定程度上解决了这个问题,我只是想删除 .join() 方法中的分隔符,以免影响最后两个值。
我最初尝试使用end=','
,但即使在最后一个值之后也放置了一个逗号。
这是我当前的代码:
def func(spam):
spam.insert(-1, "and")
print( ', '.join(spam))
return spam
example = ["apples", "bananas", "tofu", "cats"]
func(example)
This is my current output:
PS C:\Users\DELL\Desktop\.py\AutomateTheBoringStuff\chapter_4\lists> python practice1.py
apples, bananas, tofu, and, cats
预期的输出应该是:
apples, bananas, tofu and cats.
如果有比 join() 方法更好的方法,我将不胜感激。谢谢!
解决方案
推荐阅读
- java - 使用一份 Jasper 报告生成 2 个文档
- html - UI-选择默认占位符而不是可以更改
- python-3.x - DNS 查询未指定或太小
- c++ - 无法使用基类右值初始化指向子类的指针
- xml - Haskell - 如何将 XML 响应解析为 Haskell 数据类型?
- node.js - 不能在异步函数上调用 nodeify 但可以调用 then()
- android - ScrollView 内的 ConstraintLayout,constraintHeight_percent 中断滚动
- laravel - 使用 Laravel + Vue 正确处理 404 响应
- html - 在悬停时停止文本向下移动
- sql - 在年月字段中获取最近一年的记录