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.
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.
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.
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.
"&".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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With