简体   繁体   中英

not all arguments converted during string formatting - Python

I have this code:

def rndint(self, s=0, l=10):
    num = pow(self._seed, 2)
    strnum = str(num)
    if len(strnum) < 3:
        strnum + "37"
    mid = int(strnum[1:len(strnum)-1]) % l+1
    self._seed = mid
    return mid

The problem is, when I run it with:

rnd = Random(100)
rnd.rndint()

It gives:

Traceback (most recent call last):
    File "C:\Anaconda2\lib\site-packages\IPython\core\interactiveshell.py", line 3066, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
    File "<ipython-input-29-0d460ce98561>", line 1, in <module>
        rnd.rndint()
    File "C:\Users\Anshul\PycharmProjects\AMath\amath\random\randomGen.py", line 16, in rndint
        mid = int(strnum[1:len(strnum)-1]) % l+1
TypeError: not all arguments converted during string formatting

What is wrong with my code?

I think that python thinks you are trying to do string substitution, when you are intending to actually use the modulus operator. Perhaps try using parentheses around l + 1 like %(l+1) ? Not sure if that will work, but that's the only thing that seems to explain your error.

Also, I think you mean to have the line above it say:

if len(strnum) < 3:
    strnum += "37"

That also might be causing the error. Otherwise the line above it is doing nothing.

Also, this may help:

mid = int(strnum[1:-1])%(l+1)

Let me know if anything works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM