Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join list in Python but make the last separator different?

Tags:

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 

I currently have this:

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.

like image 932
daisyl Avatar asked May 06 '15 17:05

daisyl


People also ask

How do I change the separator of a list in Python?

Python String split() Method The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you join a separator in Python?

Note: The join() method provides a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by a string separator (the string on which the join() method is called) and returns the concatenated string.

How do you join a list into a string in Python?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.


1 Answers

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

I would think would work

or maybe just

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

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) 
like image 137
Joran Beasley Avatar answered Oct 11 '22 21:10

Joran Beasley