0
$\begingroup$

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]
print(
"{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?

$\endgroup$
5
  • $\begingroup$ Weird🤔;Try this :.3f.format() Author is limiting the decimals precision. $\endgroup$ – Aditya Dec 10 '19 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$ – Chicago1988 Dec 10 '19 at 2:48
  • $\begingroup$ It's not a mistake, thing's change with time but book's don't necessarily reflect that! $\endgroup$ – Aditya Dec 10 '19 at 2:49
  • $\begingroup$ out of curiosity would this have worked in python 2? $\endgroup$ – Chicago1988 Dec 10 '19 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 Dec 10 '19 at 3:11
3
$\begingroup$

Try this instead,

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

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

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

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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