Not all arguments were converted during string formatting. What does that mean?

Asked

Viewed 63 times

-4

f=open("arquivo.txt", 'w')

I’m making a code to plot a Gaussian on the random walker (Statistical Mechanic) and is giving this error when saving in the file my "Count". That is the code:

for j in range (0,t):
    count=0
    for i in range (0,100):
        x[i]=randint(0,1)
        if x[i]==1:
            count=count+1
            f.write=('0.1f\n'%(count))
f.close()

That is the mistake:

File "estat", line 23, in <module>
    f.write=('0.1f\n'%(count))
TypeError: not all arguments converted during string formatting

What can it be?

  • Please post the entire code for further verification.

  • Python is not my area, but you have tried to convert its variable count for string? The problem may be this, try so f.write=('0.1f\n'%(str(count)))

2 answers

2

Missing one % before the 0.1f. The = there is also unnecessary and would give problem. Do:

f.write('%0.1f\n'%(count))

Or with format:

f.write('{:.1f}\n'.format(count))

2

As Pedro said, its syntax has several errors. The error quoted is because you used the operator % in string, which is used for formatting, but its string does not have any template to be replaced. It is a string literal - and is the absence of % preceding the value 0.1f what causes this.

In addition, the = after the f.write will cause you to overwrite the object instead of calling it - which would not necessarily give error, but would not generate the expected result, for sure.

If you are using Python 3.6 or higher, you can use f-string:

f.write(f'{count:.1f}\n')

I talked a little bit about it here:

I also think it’s useful for you to read about contextual managers to use next to with.

So an alternative to your code would be:

with open('arquivo.txt', 'w') as f:
    for j in range (0, t):
        count = 0
        for i in range(0, 100):
            x[i] = randint(0, 1)
            if x[i] == 1:
                count = count + 1
                f.write(f'{count:.1f}\n')

This is because you can’t know exactly what the other variables are. For example, count will be an entire number, so you really need to format it as floating point?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.