Question

I know how to read bits inside an int in Python but not how to do so on a char. For an int, this elementary operation works: a & (2**bit_index) . But for a single character it gives the following error message: unsupported operand type(s) for &: 'str' and 'int'

In case, this "subtlety' matters, I'm also reading my char from a string object using:

for my_char in my_string:

I'm stressing this point, because it could be that my_char is actually a string of length one and not a char, just because I know really little about python handle of types.

Thank you.

Était-ce utile?

La solution 2

Try this instead: ord(a) & (2**bit_index).

In python there is no separate character type, a character is simply a string of size one. So if you want to perform bit manipulations with string of size 1, you can use ord() to convert it to int.

Autres conseils

You can use a bytearray instead of a string. The individual elements are integers, but you can still do basic string manipulation on the whole:

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

Correct -- it is a string of length 1 and not a char.

Convert your string to a list of integers:

>>> s = "hello world"
>>> l = [ord(c) for c in s]

Then you can use bitwise operators on specific offsets:

>>> l[1] = l[1] << 1
>>> print "".join(chr(c) for c in l)
h?llo world

Python doesn't really have char type. You have a string of length one. You need to convert it to int before you can apply those operators in it. Depending on what is in my_string this might work: int(my_char, 10)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top