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

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

I am making a code to plot a Gaussian on the random walker (Statistical Mechanics) and is giving this error when saving my "count" file. Here's 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()

This is the error:

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

What can it be?

    
asked by anonymous 20.08.2018 / 13:17

2 answers

2

% is missing before 0.1f . The% w / o% there is also unnecessary and would give problem. Make:

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

Or with = :

f.write('{:.1f}\n'.format(count))
    
20.08.2018 / 13:55
2

As Peter said, his syntax has several errors. The error quoted is because you used the % operator in string , which is used for formatting, but your string has no template to replace. It is a string literal - and is the absence of % preceding the 0.1f value that causes this.

In addition,% w / w% after% w / w% 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 mentioned some of this here:

I also think it helpful to read about context managers to use 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')

That's because you can not know for sure what the other variables are. For example, f.write will be an integer, so do you really need to format it as a floating point?

    
20.08.2018 / 14:04