Skip to main content
 首页 » 编程设计

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

2025年05月04日9emanlee

我刚开始学习 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