Reputation: 13
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
Upvotes: 1
Views: 55
Reputation: 362617
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.
Upvotes: 2
Reputation: 309891
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)
Upvotes: 2