Python字符串到整数值

2024-09-29 21:39:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何将Python中的字符串转换为相应的整数值,如下所示:

>>>print WhateverFunctionDoesThis('\x41\x42')

>>>16706

我到处找了找,但没有找到一个简单的方法。在

谢谢。在


Tags: 方法字符串整数printx41x42whateverfunctiondoesthis
3条回答

丑陋的方式:

>>> s = '\x41\x42'
>>> sum([ord(x)*256**(len(s)-i-1) for i,x in enumerate(s)])
16706

或者

^{pr2}$

如果'\x41\x42'是基于16的num,如AB。则可以使用字符串来转换它。在

import string

agaga = '\x41\x42'
string.atoi(agaga, 16)
>>> 171

对不起,如果我弄错了。。。在

>>> import struct
>>> struct.unpack(">h",'\x41\x42')
(16706,)
>>> struct.unpack(">h",'\x41\x42')[0]
16706

有关其他格式字符,请参见the documentation

相关问题 更多 >

    热门问题