1

I would like to know if there is a way to unpack values in a print statement, the same way it is possible to unpack arguments in a function f

This works:

import numpy
er = numpy.array([0.36666667, 0.46666667, 0.43333333, numpy.nan])
l = 0.8
print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (er[0], er[1], er[2], er[3], l))
# 0.367 | 0.467 | 0.433 | nan | 0.8

However, I would like to avoid multiple er[x] and instead use something like *er as in:

def f(a,b,c,d):
    return True
print(f(*er))
# True

I tried:

#print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (*(er, numpy.array([l]))))

But this last line generates "SyntaxError: invalid syntax" error.

Any ideas?

Nuageux
  • 1,668
  • 1
  • 17
  • 29

3 Answers3

4

Since you need the specific format you can do the following which allows both for the definition of separators (' | ') as well as formatting of the individual values ({:.3f}):

print(' | '.join(['{:.3f}'.format(x) for x in er]))

Adding values to that is trivial:

print(' | '.join(['{:.3f}'.format(x) for x in er]) + ' | {:.1f}'.format(l))

Note that the str.join() performs faster when provided with a list rather than a generator expression.

Ma0
  • 15,057
  • 4
  • 35
  • 65
  • *note: list comprehension is used because it's faster than genexp with `str.join`. – timgeb Jun 06 '17 at 08:15
  • The second line gives me this error - `Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate list (not "str") to list` – SRC Jun 06 '17 at 08:18
  • 1
    It should be changed to this - `print(' | '.join(['{:.3f}'.format(x) for x in er] + ['{:.1f}'.format(l)]))` – SRC Jun 06 '17 at 08:19
  • @SRC I mixed the parentheses, sorry. – Ma0 Jun 06 '17 at 08:19
2
print('{:.3f} | {:.3f} | {:.3f} | {:.1f} | {:.3f}'.format(*(list(er) + [l])))

Make sure all your args are in one place before you unpack them.

cs95
  • 379,657
  • 97
  • 704
  • 746
1

You do't want to unpack anything because you want a tuple after %.

print('%0.3f | %0.3f | %0.3f | %0.3f | %0.1f' % (tuple(er) + (1,)))
0.367 | 0.467 | 0.433 | nan | 1.0

But you'd better use str.format. Unpacking makes sense here because you want to pass every array item as an argument to the function.

print('{:0.3f} | {:0.3f} | {:0.3f} | {:0.3f} | {:0.1f}'.format(*er, 1))
0.367 | 0.467 | 0.433 | nan | 1.0
Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56