vendredi 17 juin 2016

Field spefication, format and conditional statement in Python print

I have a list mylist = [1, 2, 3] and a number n which I want to print in a specific way:

{n} {book or books} read ok: {mylist elements one by one separated by commas)

for example:

1 book read ok: 1 , 2, 3

2 books read ok: 1 , 2, 3

The decision of printing book or books depends on n, i.e. if n is 1 then print book, else print books. The code for achieving that is:

print("{:s}", "book" if n == 1 else "books")

For printing the elements of the list the code is:

print(*mylist, sep=' , ')

But, I am having problems trying to combine all of this into the desired output with including .format for displaying n as described above.

Here is what I have tried so far:

print("{0} {:s} read ok: {1}".format(n, *mylist, sep=' , '), "book" if n == 1 else "books")

which gives ValueError: cannot switch from manual field specification to automatic field numbering

Aucun commentaire:

Enregistrer un commentaire