1

The following works when I know that sample_list will hold exactly 4 items.

sample_list = ['cat', 'dog', 'bunny', 'pig']
print("Your list of animals are: {}, {}, {} and {}".format(*sample_list))

How could I format the string if I do not know the number of items that sample_list will contain at run time? This would mean that I can't enter the appropriate number of bracket place holders at design time.

2
  • 6
    If would probably be easier to just join all but the last element with commas, then join the last word onto the string with "and". Aug 24, 2018 at 13:59
  • 1
    However if you require specific formatting for each of the list elements this requires an additional mapping to the formatted elements before joining. You could also generate the format string dynamically by using len(sample_list).
    – a_guest
    Aug 24, 2018 at 14:02

4 Answers 4

5

I'd just use join

sample_list = ['cat', 'dog', 'bunny', 'pig']
printstr = '%s, and %s' % (', '.join(sample_list[:-1]), str(sample_list[-1]))
print("Your list of animals are: %s" % printstr)
1
  • 1
    you missed a bracket, and maybe the case with a list of one member can happen
    – PRMoureu
    Aug 24, 2018 at 14:11
2

If you are on the Python 3.5+ you can use f-strings like:

sample_list = ['cat', 'dog', 'bunny', 'pig']
print(f"Your list of animals are: {', '.join([item for item in sample_list[:-1]])} and {sample_list[-1]}")

f-strings are safer than using % when inputting data and more flexible than .format, for this example it makes no great difference, in my humble opinion one should get used to using them as they are superb :)

0

This might help.

sample_list = ['cat', 'dog', 'bunny', 'pig']
str_val = ""
l = len(sample_list) -1

for i, v in enumerate(sample_list):
    if i == l:
        str_val += " and {}".format(v)
    else:
        str_val += " {},".format(v)    

print("Your list of animals are: {}".format(str_val))

Or one-liner

str_val = "".join(" and {}".format(v) if i == l else " {},".format(v) for i, v in enumerate(sample_list))
print("Your list of animals are: {}".format(str_val))

Output:

Your list of animals are:  cat, dog, bunny, and pig
0

You could create the string you use format on.

sample_list = ['cat', 'dog', 'bunny', 'pig']
test='Your list of animals are: '+'{}, '*(len(sample_list)-1)+'and {}'
print(test) # Your list of animals are: {}, {}, {}, and {}
print(test.format(*sample_list)) # Your list of animals are: cat, dog, bunny, and pig

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.