Discuss / Python / 求改进

求改进

Topic source

llillz

#1 Created at ... [Delete] [Delete and Lock User]

def trim(string): if string == '': return string while string[0] == ' ' or string[-1] == ' ': if string[0] == ' ': string = string[1:] if string[-1] == ' ': string = string[:-1] if string == '': return string return string

llillz

#2 Created at ... [Delete] [Delete and Lock User]

发现了自己的一个问题,当string中包含奇数个空格时会报错,这是因为每次切片后都需要检查下string是否变成了空字符串。 修改后的代码为:

def trim(string): if string == '': return string while string[0] == ' ' or string[-1] == ' ': if string[0] == ' ': string = string[1:] if string == '': return string if string[-1] == ' ': string = string[:-1] if string == '': return string return string

不过看上去不够简洁,大家能帮忙优化下吗?

llillz

#3 Created at ... [Delete] [Delete and Lock User]

底下一位兄弟的代码给了我启发,我觉得他的思路很好,所以就把他的代码再改进了一下: def abc(s): if len(s)==0: return s else: while s[0:1]==' ': s=s[1:] while s[-1:]==' ': s=s[:-1] return s 以上代码是正确的 但是我当我做了下面修改的时候,解释器却报错了,我实在不理解。 def abc(s): if len(s)==0: return s else: while s[0]==' ': s=s[1:] while s[-1]==' ': s=s[:-1] return s 希望有人能给个解答。。

White_John

#4 Created at ... [Delete] [Delete and Lock User]

当 s = ' ' 时,你的第一个循环里是没有 s[1] 的,所以会出现索引错误

我也刚学习,我说说不一定对哈,因为s是字符串,但是你的S【0】这个操作不能直接应用吧,但是原来的S【0:1】是切片操作所以是对的。

如楼上兄弟所说,当s为空字符串时,s[0]的引用会导致越界。

s = '' s[0]

Traceback... ... IndexError: string index out of range

但同样的空字符串,s[0:1]的引用却不会导致越界

s = '' s[0:1] ''

按本章教程,s[0:1]应当理解为,从从索引0开始取,直到索引1为止(不包含索引1),也就等同于s[0]

网上也搜了一下,链接: http://python.usyiyi.cn/translate/python_352/library/stdtypes.html#text-sequence-type-str

在4.7. 文本序列类型 — str中有一段话

字符串也可以使用str构造函数从其他对象创建。

由于没有单独的“字符”类型,索引字符串会生成长度为1的字符串。也就是说,对于非空字符串s,s[0] == s[0:1]。

前面我都没看懂,但他说, 对于非空字符串s,s[0] == s[0:1] 对于非空字符串s,s[0] == s[0:1] 对于非空字符串s,s[0] == s[0:1]

我猜就是s[0:1]的操作,使得原本为空字符串的s变成了长度为1的字符串,所以s[0:1]才不会越界,但实际s[0:1]的输出仍然为空字符串。。。

验证了一下,发现理解错了

s = '' len(s) 0 len(s[0:1]) 0

YCH_2018

#8 Created at ... [Delete] [Delete and Lock User]

测试成功!!!

def trim(string): if string == '': return string while string[0] == ' ' or string[-1] == ' ': if string[0] == ' ': string = string[1:] if string[-1] == ' ': string = string[:-1] if string.isspace() == True: return '' return string

YCH_2018

#9 Created at ... [Delete] [Delete and Lock User]

666 写的太好了

YCH_2018

#10 Created at ... [Delete] [Delete and Lock User]

改一下if就行了 把 if string == '': return string 改成 if string.isspace() == True: return '' 就好了


  • 1
  • 2

Reply