利用Python重新定义一个str类使其可以完成加法和减法的操作。其中加法操作执行如下:abcdefg +acdi = abcdefgi即把加号后面的字符串没出现在前面字符串中的字符连接到字符串后面得到的新字符串为加法运算的结果。abcdefg - acdi = befg即把减号前面字符串去掉后面字符串中出现的字符剩余的字符为减法运算的结果。并可以对字符串做打印输出操作。从键盘输入两行字符串输出两
class MyStr(str):
def __init__(self, s):
self.s = s
def __add__(self, other):
res = ''
for c in self.s:
if c not in other:
res += c
return MyStr(res + other)
def __sub__(self, other):
res = ''
for c in self.s:
if c not in other:
res += c
return MyStr(res)
def __repr__(self):
return self.s
s1 = input()
s2 = input()
s1 = MyStr(s1)
s2 = MyStr(s2)
print(s1 + s2)
print(s1 - s2)
示例输入:
abcdefg
acdi
示例输出:
abcdefgi
befg
``
原文地址: http://www.cveoy.top/t/topic/eRp6 著作权归作者所有。请勿转载和采集!