以下是一个重新定义的 Str 类,实现了加法和减法的操作:

class Str(str):
    def __add__(self, other):
        new_str = self
        for char in other:
            if char not in new_str:
                new_str += char
        return new_str
    
    def __sub__(self, other):
        new_str = ''
        for char in self:
            if char not in other:
                new_str += char
        return new_str

使用示例:

s1 = Str('abcdefg')
s2 = Str('acdi')
print(s1 + s2)  # 输出abcdefgi

s3 = Str('abcdefg')
s4 = Str('bcde')
print(s3 - s4)  # 输出afg

原文地址: https://www.cveoy.top/t/topic/nZGA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录