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

1
  • Can you upload your code? You could be using isalpha on the tuple instead of the string Commented Apr 11, 2017 at 18:32

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

' '.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 :-)
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.

2 Comments

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 Added. Feel free to edit my post directly next time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.