我一直在经历Automatetheboringstuff,并遇到了一个名为逗号代码的挑战(第4章末).你必须编写一个函数,它接受一个列表并打印出一个字符串,用逗号连接元素并在最后一个元素之前添加"和".
请记住,我对python很新,或为此编程,它仍然是一个可管理的任务,但输出在插入"和"之前有一个逗号.所以我修改了代码来清理它.这是我的代码:
def comma_separator(someList):
"""The function comma_separator takes a list and joins it
into a string with (", ") and adds " and " before the last value."""
if type(someList) is list and bool(someList) is True:
return ", ".join(someList[:-1]) + " and " + someList[-1]
else:
print("Pass a non-empty list as the argument.")
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?有没有可以做到这一点的模块?