如何在 Python 中加入列表但使最后一个分隔符不同? [英] How to join list in Python but make the last separator different?

查看:57
本文介绍了如何在 Python 中加入列表但使最后一个分隔符不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果只有两个项目,或者在最后两个项目之间有逗号和一个与号,例如

I'm trying to turn a list into separated strings joined with an ampersand if there are only two items, or commas and an ampersand between the last two e.g.

Jones & Ben
Jim, Jack & James

我目前有这个:

pa = ' & '.join(listauthors[search])

并且不知道如何解决逗号/&符号问题.初学者,因此将不胜感激.

and don't know how to make sort out the comma/ampersand issue. Beginner so a full explanation would be appreciated.

推荐答案

"&".join([",".join(my_list[:-1]),my_list[-1]])

我认为可行

也许只是

",".join(my_list[:-1]) +"&"+my_list[-1]

处理边缘情况,您只能处理 2 个项目

to handle edge cases where only 2 items you could

"&".join([",".join(my_list[:-1]),my_list[-1]] if len(my_list) > 2 else my_list)

这篇关于如何在 Python 中加入列表但使最后一个分隔符不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆