码迷,mamicode.com
首页 > 其他好文 > 详细

练习:字符串减法

时间:2017-04-10 21:51:40      阅读:625      评论:0      收藏:0      [点我收藏+]

标签:mos   class   练习   rac   super   self   str   报错   err   

字符串加法会将两个字符串连接

>>> a = " 我是超级 "

>>> b = "因为我内裤外穿了"

>>> a + b
‘ 我是超级 因为我内裤外穿了‘

但遗憾的是 字符串减法会抛出异常。

 

定义一个类,支持字符串减法: A - B。 从A中去除所有B的子字符串。

class Nstr(str):

    def __sub__(self , other):

        return self.replace(other , "")

 

本人错误:

>>> a = " l am a superman"

>>> b = "super"

>>> a - b

Traceback (most recent call last):

  File "<pyshell#27>", line 1, in <module>

    a - b

TypeError: unsupported operand type(s) for -: str and str

 

写完上面的类之后,直接调用减法,错误错误错误。
这么写a,b的类型还是str,  str本身没减法,所以报错误。

>>> type(a)

<class str>

>>> type(b)

<class str>

 

正确方法:

>>> a = Nstr("l am a superman")

>>> b = Nstr("super")

>>> a - b

l am a man

 

练习:字符串减法

标签:mos   class   练习   rac   super   self   str   报错   err   

原文地址:http://www.cnblogs.com/marianyad/p/6690694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!