在Python中,将二进制字符串转换为其他形式主要有以下两种方法,具体实现如下:
一、字符串转二进制字符串(字符级)
通过获取字符的ASCII码(使用 `ord`),再转换为二进制字符串(使用 `bin`),最后拼接处理。 ```python
def encode(s):
return ' '.join([bin(ord(c)).replace('0b', '') for c in s])
```
示例:
```python
print(encode('hello')) 输出: 1101000 1100101 1101100 1101100 1101111
```
方法二:使用 `format` 函数
通过 `format` 函数直接将字符格式化为二进制字符串。 ```python
def encode(s):
return ' '.join(format(ord(c), '08b') for c in s)
```
示例:
```python
print(encode('hello')) 输出: 1101000 1100101 1101100 1101100 1101111
```
二、二进制字符串转其他形式
转整数
使用 `int` 函数,指定基数为2进行转换。 ```python
binary_str = '1101000'
number = int(binary_str, 2)
print(number) 输出: 108
```
转字符
将二进制字符串按8位分组,转换为整数后再使用 `chr` 函数。 ```python
def decode(s):
return ''.join(chr(int(b, 2)) for b in s.split())
```
示例:
```python
print(decode('1101000 1100101 1101100 1101100 1101111')) 输出: hello
```
三、注意事项
位数对齐: 若需固定长度(如8位),可使用 `zfill` 补齐前导零。- 效率优化