# Why I get AttributeError: 'float' object has no attribute '3f'?

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?

• Weird🤔;Try this :.3f.format() Author is limiting the decimals precision. – Aditya Dec 10 '19 at 2:44
• wow, it works! Is the ':' always required for this formatting? why the author has a mistake on the very first example of the book?? – Chicago1988 Dec 10 '19 at 2:48
• It's not a mistake, thing's change with time but book's don't necessarily reflect that! – Aditya Dec 10 '19 at 2:49
• out of curiosity would this have worked in python 2? – Chicago1988 Dec 10 '19 at 3:04
• 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! – Aditya Dec 10 '19 at 3:11

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


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

• Well, to be honest I thought the book was the 'latest doc' so far, it was written only last year! – Chicago1988 Dec 10 '19 at 3:14
• It will soon be 2 years old then.. – Aditya Dec 10 '19 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.