1

I have a list of objects,

l = (('a1', 1.96256684), ('b3', 1.36), ('e2', 0.5715))

I want to be able to format the numbers to a certain number of decimal places (4) in order to get an output like

a1 1.9626 b3 1.3600 e3 0.5715

I tried the method described here (using isalpha) but get the error

AttributeError: 'tuple' object has no attribute 'isalpha'

I'm wondering if it's because the alphabetic letters have numbers attached to them? But then I would think it would just return False instead of giving me an error.

Thank you for any help or adivce

Community
  • 1
  • 1
teatag
  • 13
  • 2

2 Answers2

2

You probably want to format the strings using .format.

>>> '{:0.4f}'.format(1.36)
'1.3600'
>>> '{:0.4f}'.format(1.96256684)
'1.9626'

The full code could look something like:

' '.join('{} {:0.4f}'.format(*t) for t in l)
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • `' '.join('{0[0]} {0[1]:0.4f}'.format(t) for t in l)` also works and avoids the tuple unpacking, but I don't like it as much :-) – mgilson Apr 11 '17 at 18:35
2

Print statement will join with spaces anyway, so you can unpack the args with a splat:

>>> print(*(f'{s} {f:.4f}' for s,f in l))
a1 1.9626 b3 1.3600 e2 0.5715

This uses the literal string interpolation feature, new in Python 3.6.

wim
  • 338,267
  • 99
  • 616
  • 750
  • You might want to point out t hat this is python3.6+ only -- And you might want to mention that you are using f-strings. I appreciate their use, but it's probably good to give people something to google to find out more :-). – mgilson Apr 11 '17 at 18:41
  • @mgilson Added. Feel free to edit my post directly next time. – wim Apr 11 '17 at 18:42