开发者

Python string to integer value

I'd like to know how to convert strings in Python to their corresponding integer values, like so:

>>>print WhateverFunctionDoesThis('\x开发者_运维百科41\x42')

>>>16706

I've searched around but haven't been able to find an easy way to do this.

Thank you.


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

For other format chars see the documentation


If '\x41\x42' is 16-based num, like AB. You can use string to convert it.

import string

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

Sorry if i got you wrong...


ugly way:

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

or

>>> sum([ord(x)*256**i for i,x in enumerate(reversed(s))])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜