是否可以在Python中对字符串进行按位运算? [英] Is it possible to do bitwise operations on a string in Python?

查看:405
本文介绍了是否可以在Python中对字符串进行按位运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这失败了,不足为奇:

>>> 'abc' << 8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for <<: 'str' and 'int'
>>> 

在ascii abc等于0110000101100010011000116382179的情况下,是否有办法将其任意移动,以使'abc' << 801100001011000100110001100000000?

With ascii abc being equal to 011000010110001001100011 or 6382179, is there a way to shift it some arbitrary amount so 'abc' << 8 would be 01100001011000100110001100000000?

其他按位运算又如何呢? 'abc' & 63 = 100011等?

What about other bitwise operations? 'abc' & 63 = 100011 etc?

推荐答案

您可能想要的是位串模块(请参见 http://code.google.com/p/python-bitstring/).它似乎支持按位运算以及其他一些对位数组的操作.但是您应该小心地在其中输入字节(例如b'abc'bytes('abc')),而不要输入字符-字符可以包含Unicode并占用多个字节.

What you probably want is the bitstring module (see http://code.google.com/p/python-bitstring/). It seems to support bitwise operations as well as a bunch of other manipulations of bit arrays. But you should be careful to feed bytes into it (e.g. b'abc' or bytes('abc')), not characters - characters can contain Unicode and occupy more than one byte.

这篇关于是否可以在Python中对字符串进行按位运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆