Skip to main content
 首页 » 编程设计

Python:操作字符串中字符中的位

2025年05月04日22unruledboy

我知道如何在 Python 中读取 int 中的位,但不知道如何在 char 中读取。 对于 int,此基本操作有效: a & (2**bit_index) 。但对于单个字符,它会给出以下错误消息:unsupported operand type(s) for &: 'str' and 'int'

以防万一,这种“微妙”很重要,我还使用以下方法从字符串对象中读取我的字符:

for my_char in my_string: 

我强调这一点,因为 my_char 实际上可能是一个长度为 1 的字符串而不是 char,只是因为我对 python 类型句柄知之甚少。

谢谢。

请您参考如下方法:

您可以使用 bytearray 代替字符串。单个元素是整数,但您仍然可以对整体进行基本的字符串操作:

>>> arr = bytearray('foo') 
>>> type(arr[0]) 
<type 'int'> 
>>> arr.replace('o', 'u') 
bytearray(b'fuu')