Home > OS >  How do I add 'and' at the end of the list element
How do I add 'and' at the end of the list element

Time:06-04

num = [1, 2, 3, 4].
Suppose I have a list named 'num'.

I want to print the list this way: 1, 2, 3, and 4.
How do I add 'and' at the end like that?

CodePudding user response:

I'd suggest you to use python's enumerate() function. You can read more about it here: https://docs.python.org/3/library/functions.html#enumerate

This allows us to iterate through the list, but simultaneously keeping track of the index. This is useful because, when the index shows that we are at the last element of the list, which means our index is at len(num)-1, we should output an "and" in front of it (and a full stop . behind it, which is what is shown in your example.

You could do something like this:

for index, x in enumerate(num):
    if index != len(num)-1: #not the last number
        print("{}, ".format(x), end = "");
    else: #the last number
        print("and {}.".format(x), end = "");

This yields the output:

1, 2, 3, and 4.

CodePudding user response:

The normal way in Python to insert delimiters like a comma into a list of strings is to use join():

>>> ", ".join(str(x) for x in num)
'1, 2, 3, 4'

but you want and after the last comma:

>>> prefix, _, suffix = ", ".join(str(x) for x in num).rpartition(" ")
>>> print (prefix,"and",suffix)
1, 2, 3, and 4
  • Related