从模 Python 返回值时如何保持前导零
How to keep leading zero when returning value from modulo Python
我想构建一个程序,允许用户输入一个数字,然后使该数字以 2 为指数。此外,用户还可以输入要查看的最终数字的最后几位数字。这是我的代码:
exponent = eval(input('Type in exponent '))
lastDigits = eval(input('Type in how many digits you want to see'))
number = 2**exponent
print(number /int(('1'+('0'*lastDigits))))
例如输出是:
输入指数 = 10
输入您要查看的位数 = 3
问题来了。
如果我的指数是 10 那意味着 2**10 = 1024
我想看到最后 3 位数字,即 024,但 Python 不保留前导零,所以我只得到 24。我该如何解决这个问题?
我会使用字符串运算而不是整数运算:
exponent = int(input('Type in exponent '))
lastDigits = int(input('Type how many digits you want to see '))
number = 2 ** exponent
cropped = str(number)[-lastDigits:]
print(cropped) # Result: "024"
我基本上只是在 number
的字符串表示中切掉除最后 lastDigits
个字符以外的所有字符,这样我们就包含了所有前导零。
我也转而使用 int
转换而不是 eval
函数,因为如果有人决定将破坏性的东西放入输入中,eval
函数可能存在潜在危险。
我想构建一个程序,允许用户输入一个数字,然后使该数字以 2 为指数。此外,用户还可以输入要查看的最终数字的最后几位数字。这是我的代码:
exponent = eval(input('Type in exponent '))
lastDigits = eval(input('Type in how many digits you want to see'))
number = 2**exponent
print(number /int(('1'+('0'*lastDigits))))
例如输出是: 输入指数 = 10 输入您要查看的位数 = 3
问题来了。 如果我的指数是 10 那意味着 2**10 = 1024 我想看到最后 3 位数字,即 024,但 Python 不保留前导零,所以我只得到 24。我该如何解决这个问题?
我会使用字符串运算而不是整数运算:
exponent = int(input('Type in exponent '))
lastDigits = int(input('Type how many digits you want to see '))
number = 2 ** exponent
cropped = str(number)[-lastDigits:]
print(cropped) # Result: "024"
我基本上只是在 number
的字符串表示中切掉除最后 lastDigits
个字符以外的所有字符,这样我们就包含了所有前导零。
我也转而使用 int
转换而不是 eval
函数,因为如果有人决定将破坏性的东西放入输入中,eval
函数可能存在潜在危险。