0

I have data that I want to print to file. For missing data, I wish to print the mean of the actual data. However, the mean is calculated to more than the required 4 decimal places. How can I write to the mean to file and format this mean at the same time?

I have tried the following, but keep getting errors:

outfile.write('{0:%.3f}'.format(str(mean))+"\n")
2
  • 2
    What errors are you getting ? Commented Nov 30, 2013 at 0:55
  • ValueError: Invalid conversion specification Commented Nov 30, 2013 at 0:56

4 Answers 4

3

First, remove the % since it makes your format syntax invalid. See a demonstration below:

>>> '{:%.3f}'.format(1.2345)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid conversion specification
>>> '{:.3f}'.format(1.2345)
'1.234'
>>>

Second, don't put mean in str since str.format is expecting a float (that's what the f in the format syntax represents). Below is a demonstration of this bug:

>>> '{:.3f}'.format('1.2345')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'f' for object of type 'str'
>>> '{:.3f}'.format(1.2345)
'1.234'
>>>

Third, the +"\n" is unnecessary since you can put the "\n" in the string you used on str.format.

Finally, as shown in my demonstrations, you can remove the 0 since it is redundant.


In the end, the code should be like this:

outfile.write('{:.3f}\n'.format(mean))
Sign up to request clarification or add additional context in comments.

2 Comments

Problem with "f" now unfortunately. I'm guessing the string conversion is a problem too.
@stars83clouds - Oh yes, I missed that. You need to not convert mean to a string. See my edit.
1

You don't need to convert to string using str(). Also, the "%" is not required. Just use:

outfile.write('{0:.3f}'.format(mean)+"\n")

Comments

0

First of all, the formatting of your string has nothing to do with your write statement. You can reduce your problem to:

string = '{0:%.3f}'.format(str(mean))+"\n"
outfile.write(string)

Then, your string specification is incorrect and should be:

string = '{0:.3f}\n'.format(mean)

Comments

0
outfile.write('{.3f}\n'.format(mean))

Comments

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.