简体   繁体   中英

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

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM