gpt4 book ai didi

python - 在python中将变量放在引号内

转载 作者:太空宇宙 更新时间:2023-11-04 06:56:30 25 4
gpt4 key购买 nike

我刚开始学习 Python。我试图让用户输入一个数字基数和一个数字,并将其转换为十进制。

我一直在尝试像这样使用内置的 int 函数:

base = raw_input("what number base are you starting with?  \n")
num = raw_input("please enter your number: ")
int(num,base)

我的问题是,当您使用该 int 函数时,您转换的数字需要用引号引起来,如下所示:int('fff',16)

当我使用变量时如何完成此操作?

最佳答案

不需要引号。引号不是字符串的一部分。

>>> int('fff',16)
4095
>>> da_number = 'fff'
>>> int(da_number, 16)
4095

但是,您需要将基数转换为整数。

>>> base = '16'
>>> int(da_number, base) # wrong! base should be an int.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> int(da_number, int(base)) # correct
4095

关于python - 在python中将变量放在引号内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15074977/

25 4 0