1. 程式人生 > 實用技巧 >python3:數字/字串之間的變換

python3:數字/字串之間的變換

由於在python2中的命令encode和decode已經不在適用python3

def string2number(str):
    """Convert a string to a number

    Input:  string(big-endian)
    Output: long or integer
    """
    return int(str.encode('hex'),16)


mypresent.py", line 36, in string2number
    return int(str.encode('hex'),16)
LookupError: 
'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs

所以特地學習python中的數字表示方法,

binary二進位制(0b101)、

octal八進位制(0o74125314)、

decimal十進位制(1223)、

hexadecimal十六進位制(0xff)

而且可以為加下來做分組加密打下coding基礎

bin(number)

'''

input -- a number: 輸入引數可以為二進位制數、八進位制數、十進位制數、十六進位制數

output -- a string: 輸出為以0b開頭的二進位制字串

'''

example:

>>> bin(0x11) 
'0b10001'
>>> bin(0b1010111) 
'0b1010111'
>>> bin(0o1234567) 
'0b1010011100101110111'
>>> bin(1234567)   
'0b100101101011010000111'
>>> bin(0x1234f567ff)
'0b1001000110100111101010110011111111111'
>>> bin(bin(123))
Traceback (most recent call last):
  File "<stdin>
", line 1, in <module> TypeError: 'str' object cannot be interpreted as an integer >>>

oct(number)

'''

input -- a number: 輸入引數可以為二進位制數、八進位制數、十進位制數、十六進位制數

output -- a string: 輸出為以0o開頭的二進位制字串

'''

example:

>>> oct(0b1111) 
'0o17'
>>> oct(0o1111) 
'0o1111'
>>> oct(1111)   
'0o2127'
>>> oct(0xff1111) 
'0o77610421'
>>> oct(oct(0xff1111))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>>

oct(number)

'''

input -- a number: 輸入引數可以為二進位制數、八進位制數、十進位制數、十六進位制數

output -- a string: 輸出為以0x開頭的二進位制字串

'''

example:

>>> hex(0b1111)        
'0xf'
>>> hex(0o1111) 
'0x249'
>>> hex(1111)   
'0x457'
>>> hex(0x1111) 
'0x1111'
>>> hex(hex(0x1111))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>>

int(number)

'''

input -- a number: 輸入引數可以為二進位制數、八進位制數、十進位制數、十六進位制數、浮點數

output -- a string: 輸出整數,浮點數向下取整

'''

建構函式如下:

int(x=0) --> integer

int(x, base=10) --> integer 給定了引數base(取0,2-36) x必須是字串形式、bytes

example:

>>> int('ffff',16) 
65535
>>> int('ffff',8)  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 8: 'ffff'
>>> int('ffff',36) 
719835
>>> int(b'ffff',18) 
92625
>>> int(b'ffff',16) 
65535
>>>