2

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.

1
  • 2
    ', '.join(a[:-1]) + 'and ' + a[-1] might be your best bet. There is no builtin function that does this. Commented Dec 7, 2012 at 6:05

4 Answers 4

6

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]
Sign up to request clarification or add additional context in comments.

1 Comment

This solution doesn't take into account empty lists or lists with just one element
3

SnakesAndCoffee has the best way(s). Another (less useful) way:

>>> a = ['hello1', 'hello2', 'hello3']
>>> ' and '.join((', '.join(a[:-1]), a[-1]))
'hello1, hello2 and hello3'

Here you are using two joins - the inner join joins every element up until the second to last element with a comma. That string is then joined to the last element (a[-1]) using the outer join, which is and.

2 Comments

Thanks for an alternative method.
@TheDragonAce No problem at all :)
3

You need to handle small lists as special cases:

def my_function(a):
    if a == []:
        return ""
    elif len(a) == 1:
        return a[0]
    else:
        return ', '.join(a[:-1])+' and '+ a[-1]

Comments

-1
list=[] for i in range(no):   for j in range(no-i):
      list.append(j+1);   if(i!=0):
      for a in range(2*i-1):
          list.append(" ");   for k in range(no-i,0,-1):
      if(i==0 and k==no):
          pass;
      else:
          list.append(k);   list.append("\n");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.