Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .join() in Python

Tags:

python

Very simple and quick question. Take this list for example:

a = ['hello1', 'hello2', 'hello3']
','.join(a)

I would like to have 'and' instead of a comma before the last element of the list. So I would get:

hello 1, hello 2 and hello 3

instead of....

hello 1, hello 2, hello 3

Is there a way to accomplish this using .join()? I know I can just type it in the list for a simple example like this, but the list I need in my actual program comes from user input.

like image 751
Ace Avatar asked Jan 23 '26 11:01

Ace


1 Answers

In essence, you want to manipulate the two parts of the list separately, the first consisting of everything except the last string, and the other consisting of just the last one.

def my_func(lst):
    return ', '.join(lst[:-1])+' and '+lst[-1]

or using a lambda:

f = lambda x: ', '.join(x[:-1]) + ' and '+x[-1]

or if you just want it run once:

result = ', '.join(a[:-1]) + ' and ' + a[-1]
like image 169
Snakes and Coffee Avatar answered Jan 25 '26 01:01

Snakes and Coffee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!