0

Hi I am trying to understand how the string formatting works with float:

I have tried

>>> print("%s %s %s %s %-9.10f"%("this","is","monday","morning",56.3648)) 

it gives output of

this is monday morning 56.3648000000 

however this,

>>> print("%s %s %s %s %10f"%("this","is","monday","morning",56.3648)) 

gives output of

this is monday morning 56.364800 

what is causing the difference?

1 Answer 1

2

The way the pattern strings are parsed. %9.10f sets the (minimum) field width to 9 and the precision to 10, while %10f only sets the width to 10. I think you meant to write %.10f instead:

In [4]: '%10f' % 56.3648 # width Out[4]: ' 56.364800' In [5]: '%.10f' % 56.3648 # precision Out[5]: '56.3648000000' 

Also, consider using the newer str.format formatting style. Your first example would turn into

In [6]: '{} {} {} {} {:<9.10f}'.format('this', 'is', 'monday', 'morning', 56.3648) Out[6]: 'this is monday morning 56.3648000000' 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.