Python 模数给出字符串格式错误 [英] Python Modulus Giving String Formatting Errors

查看:60
本文介绍了Python 模数给出字符串格式错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 中执行一个值的模数,但我收到错误,因为它根据我的知识将模数解释为字符串格式常量.我最初的猜测是输入这个,但它挂了.

I'm trying to perform the modulus of a value in python, but I'm getting errors as it's interpretting the modulus as a string formatting constant, from my knowledge. My initial guess would be to type cast this, but then it hangs.

    val = pow(a,n,p)
    val = y1*val
    val = val % p

是这道题对应的两行代码吗?现在,当我运行它时,我得到:类型错误:并非所有参数都在字符串格式化期间转换在第二行.

Are the two lines of code corresponding to this question. Right now, when I run this, I get: TypeError: not all arguments converted during string formatting At the second line.

如果我将 val 包装成一个整数并输入它......计算需要很长时间.

If I wrap val into an integer and type cast it...it takes extremely long to calculate.

我对 python 不太熟练,我猜我错过了一些简单的东西,但是什么?

I'm not too skilled with python, my guess is I'm missing something simple, but what?

推荐答案

如果出现这个错误,y1 本身就是一个字符串.你不能用字符串执行数字计算——当你做int(y1)"时——它不是强制转换,而是将字符串中的字符表示的数字转换为实际数值——这是唯一的方法对其进行数值运算.

If yu are getting this error, y1 itself is a string. You can't perform numeric calculations with strings - when you do "int(y1) " - it is not casting, it is converting the number represented by characters inside the string o an actual numeric value - and that is the only way you can perform numeric operations on it.

如果它是 takin thta log,很可能是因为您正在尝试将 "y1 * val" 转换为 int - 这已经是错误的 - 如果 y1 是一个字符串,则 "y1 * val" 会给你 y1 连接到自身 "val"次——所以这将是一个非常大的数字.在乘法之前,您需要将y1"中的值作为数字 - 如:

If it is takin thta log, it is probable because you are trying convert "y1 * val" to int - which is wrong already - if y1 is a string, "y1 * val" gives you y1 concatenated to itself "val" times - so it would be a really huge number. You need to have the value i n "y1" as a number before multiplying - as in:

val  = int(y1) * val

这篇关于Python 模数给出字符串格式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆