Post

Python Note - 02

Posted
By 9vvert
1 min read
Python Note - 02

str, byte, int转换

str -> int 使用int函数:
1
2
x = int("43")
y = int("0xff", 16)

而使用base = 0可以自动探测前缀:

1
2
x = int("0x43", 0)      # 67
y = int("43", 0)        # 43
int -> str 普通十进制:
1
2
3
4
s1 = int(63)    # "63"
s2 = hex(48)    # "0x30"
s3 = bin(15)    # "0b1111"
s4 = oct(10)    # "0o12"

另外可以使用自定义的base format:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
format(255, "x")
# "ff"
format(255, "#x")
# "0x42"
format(255, "X")
# "FF"
format(255, "#X")
# "0XFF"
format(66, "b")
# "1000010"
format(66, "#b")
# "0b1000010"
format(66, "o")
# "102"
format(66, "#o")
# "0o102"
format(66, "d")
# "66"
int <-> bytes int.to_bytes
1
2
3
4
5
6
7
n = 0x12345678
b1 = n.to_bytes(4, "big")
print(b1)
# b'\x12\x34\x56\x78'
b2 = n.to_bytes(4, "little")
print(b2)
# b'\x78\x56\x34\x12'

int.from_bytes

1
2
3
4
b = b"\x78\x56\x34\x12"
n = int.from_bytes(b, "little")
print(hex(n))
# 0x12345678
  • normal str <-> bytes 使用 .encode().decode(),还可以指定某些编码,比如utf-8

  • hex str <-> bytes bytes.fromhex()
    1
    2
    3
    4
    
    hex_s = "41424344"
    b = bytes.fromhex(hex_s)
    print(b)
    # b'ABCD'
    

    注意可以用removeprefix来删除字符的前缀:

    1
    2
    3
    4
    
    hex_s = "0x41424344"
    b = bytes.fromhex(hex_s.removeprefix("0x"))
    print(b)
    # b'ABCD'
    

    str.hex()

    1
    2
    3
    4
    
    b = b"ABCD"
    hex_s = b.hex()
    print(hex_s)
    # 41424344
    
    programming-language, python
    This post is licensed under CC BY 4.0 by the author.