|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- class Word(str):
- '''存储单词的类,定义比较单词的几种方法'''
- def __new__(cls, word):
- # 注意我们必须要用到 __new__ 方法,因为 str 是不可变类型
- # 所以我们必须在创建的时候将它初始化
- if ' ' in word:
- print "Value contains spaces. Truncating to first space."
- word = word[color=Red][:word[/color].index(' ')] #单词是第一个空格之前的所有字符
- return str.__new__(cls, word)
- def __gt__(self, other):
- return len(self) > len(other)
- def __lt__(self, other):
- return len(self) < len(other)
- def __ge__(self, other):
- return len(self) >= len(other)
- def __le__(self, other):
- return len(self) <= len(other)
复制代码
那里为什么还要用切片啊 直接 word = word.index(' ')
不就行了吗?
本帖最后由 jackz007 于 2020-11-22 20:02 编辑
word = word.index(' ') 只能得到字符串中第一个空格字符的索引值。这并不是我们所需要的。word 有可能包含有多个单词,如果是这样,那么,单词之间会有一个空格隔开,我们的意图是通过字符串切片,从字符串开头一直切到第一个空格位置,从而得到字符串中的第一个单词。
这一句
- word = word[:word.index(' ')]
复制代码
如果这么写可能比较好理解:
- word = word . strip() . split()[0]
复制代码
|
|