简体   繁体   中英

How to add a word before the last word in list?

Hello I'm new to this programming language

I wanted to add the word 'and' before the last item in my list.

For example:

myList = [1,2,3,4]

If I print it the output must be like:

1,2,3 and 4

Here is one way, but I have to convert the int's to strings to use join :

myList = [1,2,3,4]
smyList = [str(n) for n in myList[:-1]]   
print(",".join(smyList), 'and', myList[-1])

gives:

1,2,3 and 4

The -1 index to the list gives the last (rightmost) element.

This may not be the most elegant solution, but this is how I would tackle it.

define a formatter function as follows:

def format_list(mylist)
    str = ''
    for i in range(len(mylist)-1):
        str.append(str(mylist[i-1]) + ', ')

    str.append('and ' + str(mylist[-1]))

    return str

then call it like this

>>> x = [1,2,3,4]
>>> format_list(x)
1, 2, 3, and 4

You can also use string formating:

l = [1,2,3,4]
print("{} and {}".format(",".join(str(i) for i in l[:-1]), l[-1]))
#'1,2,3 and 4'

Using join (to join list elements) and map(str,myList) to convert all integers inside list to strings

','.join(map(str,myList[:-1])) + ' and ' + str(myList[-1])
#'1,2,3 and 4'

Your question is misleading, if you are saying "How to add a word before the last word in list?" it means you want to add 'and' string before last item in the list , while many people are giving answer using .format() method , You should specify you want 'and' for printing or in list for further use of that result :

Here is list method according to your question :

myList = [1,2,3,4]
print(list((lambda x,y:(x+['and']+y))(myList[:-1],myList[-1:])))

output:

[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