如何在 Python 中将变量转换为 denary?

How can you convert a variable into denary in Python?

我在将字符串(如输入)转换为 denary 时遇到了问题,因为字符串是使用十六进制所必需的(因为它不能存储为整数,因为包含字符 a-f)。这里有两个不起作用的尝试:

>>> hex_number = 'ff' #(255 in denary)
>>> ascii(0xhex_number)
SyntaxError: invalid hexadecimal literal
>>> ascii('0x'+hex_number)
"'0xff'"

我还看到您可以使用 format() 以某种方式使用,但这也不起作用。

>>> format(hex_number, '16') #This was what the demo said to do.
'ff              '

如何才能将 hex_number(十六进制)转换为十进制(也称为十进制)或任何其他 n 基数字系统?

将字符串变成 int 然后再变成字符串

>>> n = int('ff', 16); n
255
>>> f'{n:d}'
'255'