Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - short way to unpack list for string formatting operator?

Variations of the * or ** operators don't seem to work, unfortunately:

lstData = [1,2,3,4]
str = 'The %s are %d, %d, %d, and %d' % ('numbers', *lstData)

Is there an easy way?

like image 926
user1012037 Avatar asked Nov 02 '11 09:11

user1012037


People also ask

How do I format a list to a string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

What is .2f in Python?

As expected, the floating point number (1.9876) was rounded up to two decimal places – 1.99. So %. 2f means to round up to two decimal places. You can play around with the code to see what happens as you change the number in the formatter.

What is __ format __ in Python?

The object.__format__ method is the simplest: It simply converts the object to a string, and then calls format again: class object: def __format__(self, format_spec): return format(str(self), format_spec) The __format__ methods for 'int' and 'float' will do numeric formatting based on the format specifier.


2 Answers

Use format:

str = 'The {} are {}, {}, {}, and {}'.format('numbers', *lstData)

see the docs for more details about possible formatting (floats, decimal points, conversion, ..).

like image 111
rplnt Avatar answered Oct 23 '22 07:10

rplnt


s = 'The %s are %d, %d, %d, and %d' % tuple(['numbers'] + lstData)
like image 34
edvaldig Avatar answered Oct 23 '22 07:10

edvaldig