I am getting this error:

AttributeError: 'float' object has no attribute '3f'

I don't understand why I am getting it, I am following the example straight from the book "applied text analysis"

The chunk of code in python is:

total = sum(words.values())
for gender, count in words.items():
pcent = (count / total) * 100
nsents = sents[gender]
"{0.3f}% {} ({} sentences)".format(pcent, gender, nsents)

I see that pcent clearly will return a float, why the author tries to apply .3f what am I missing?

  • $\begingroup$ Weird🤔;Try this :.3f.format() Author is limiting the decimals precision. $\endgroup$
    – Aditya
    Commented Dec 10, 2019 at 2:44
  • $\begingroup$ wow, it works! Is the ':' always required for this formatting? why the author has a mistake on the very first example of the book?? $\endgroup$ Commented Dec 10, 2019 at 2:48
  • $\begingroup$ It's not a mistake, thing's change with time but book's don't necessarily reflect that! $\endgroup$
    – Aditya
    Commented Dec 10, 2019 at 2:49
  • $\begingroup$ out of curiosity would this have worked in python 2? $\endgroup$ Commented Dec 10, 2019 at 3:04
  • $\begingroup$ I am not actually sure but in very early days Python had introduced % formatting (similar to C/C++ etc), after that in Py2.x they introduced string formatting (the example you have imho) and then in Py3.6+ they introduced the f-strings! Prefer fstrings always unless you are logging something where that string formatting comes more handy! $\endgroup$
    – Aditya
    Commented Dec 10, 2019 at 3:11

2 Answers 2


Try this instead,

"{:.3f}% {} ({} sentences)".format(pcent, gender, nsents)

Refer the latest docs for more examples and check the Py version!

  • $\begingroup$ Well, to be honest I thought the book was the 'latest doc' so far, it was written only last year! $\endgroup$ Commented Dec 10, 2019 at 3:14
  • 1
    $\begingroup$ It will soon be 2 years old then.. $\endgroup$
    – Aditya
    Commented Dec 10, 2019 at 3:23

You could also use {:.3%} instead of {:.3f}%.

It will transform the value into percentages automatically. That means "{:.3%}".format(0.3) will print "30%" while you have to write "{:.3f}%".format(0.3 * 100) to get "30%" as well.


Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.