|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我想用一个笨办法去计算字符串的相减,但是结果却没有达到预期,想知道原因,请教各位资深大佬,附代码:
- class Nstr(str):
- def __sub__(self, other):
- a = list(self)
- c = str()
- count = 0
- num = a.count('i')
- print('总共有{}处相同'.format(num))
- for each_other in a:
- if each_other == other:
- count += 1
- a.remove(each_other)
- print('第{}次删除!a => {}'.format(count, a))
- for each_a in a:
- c += each_a
- return c
- a = Nstr('I love FishC. com!iiiiiiii')
- b = Nstr('i')
- print(a - b)
复制代码
运行后结果如图:
总共有9处相同
第1次删除!a => ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'F', 's', 'h', 'C', '.', ' ', 'c', 'o', 'm', '!', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i']
第2次删除!a => ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'F', 's', 'h', 'C', '.', ' ', 'c', 'o', 'm', '!', 'i', 'i', 'i', 'i', 'i', 'i', 'i']
第3次删除!a => ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'F', 's', 'h', 'C', '.', ' ', 'c', 'o', 'm', '!', 'i', 'i', 'i', 'i', 'i', 'i']
第4次删除!a => ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'F', 's', 'h', 'C', '.', ' ', 'c', 'o', 'm', '!', 'i', 'i', 'i', 'i', 'i']
第5次删除!a => ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'F', 's', 'h', 'C', '.', ' ', 'c', 'o', 'm', '!', 'i', 'i', 'i', 'i']
运行后的结果为:I love FshC. com!iiii
看这里: https://fishc.com.cn/thread-158978-1-1.html
以下代码完美解决你的问题:
- class Nstr(str):
- def __sub__(self, other):
- a = list(self)
- c = str()
- count = 0
- num = a.count('i')
- print('总共有{}处相同'.format(num))
- for each_other in a[:]: # 修改
- if each_other == other:
- count += 1
- a.remove(each_other)
- print('第{}次删除!a => {}'.format(count, a))
- for each_a in a:
- c += each_a
- return c
- a = Nstr('I love FishC. com!iiiiiiii')
- b = Nstr('i')
- print(a - b)
复制代码
|
|