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?
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.
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.
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.
Use format:
str = 'The {} are {}, {}, {}, and {}'.format('numbers', *lstData)
see the docs for more details about possible formatting (floats, decimal points, conversion, ..).
s = 'The %s are %d, %d, %d, and %d' % tuple(['numbers'] + lstData)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With