课后作业第42讲动动手第1题解答
题目为:1. 移位操作符是应用于二进制操作数的,现在需要你定义一个新的类 Nstr,也支持移位操作符的运算:
>>> a = Nstr('I love FishC.com!')
>>> a << 3
>>> ’ove FishC.com!I l'
>>> a >> 3
>>>'om!I love FishC.c'
题目解答未考虑当移位数大于字符串长度的情形,我觉得正确解答如下:
class Nstr(str):
def __lshift__(self,other):
if other <=len(self):
return self + self[:other]
else:
return self[(other%len(self)):]+self[:(other%len(self))]
def __rshift__(self,other):
if other <=len(self):
return self[-other:]+self[:-other]
else:
return self[-(other%len(self)):]+self[:-(other%len(self))]
页:
[1]