1

My question is a continuation of Print list without brackets in a single row and How to print a list without brackets

From the second question I would like to be able to print a specific format, similar to using

print(f'{10.1234567:.2f} units')

So from

Floatlist = [14.715258933890,10.215953824,14.8171645397,10.2458542714719]
print (", ".join(map(str, Floatlist)))

we get

14.71525893389, 10.215953824, 14.8171645397, 10.2458542714719

but I would like to get

14.72, 10.22, 14.82, 10.25

or even

14.72 units, 10.22 units, 14.82 units, 10.25 units

Again, using a single line of code, as the above questions

Ps. I know that putting the units in the ', ' as ' units, ' we will not get the units on the last item.

Thanks

Dimitris
  • 21
  • 2

2 Answers2

3

You just need to change the map operation, to a more precise one

floatlist = [14.715258933890,10.215953824,14.8171645397,10.2458542714719]
print(", ".join(map(lambda x : str(round(x, 2)), floatlist))) # for only 2 decimals

print(", ".join(map(lambda x : f'{x:.2f} units', floatlist))) # for 2 decimales + 'units'

Note : Function and variable names

azro
  • 53,056
  • 7
  • 34
  • 70
0

Use str.format with str.join:

Floatlist = [14.715258933890,10.215953824,14.8171645397,10.2458542714719]
print( ', '.join( '{:.2f} units'.format(v) for v in Floatlist ) )

Prints:

14.72 units, 10.22 units, 14.82 units, 10.25 units
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91