Discuss / Python / 掉了个坑

掉了个坑

Topic source

Barnett007

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

正解1:

def trim(s): while s[:1] == ' ': s = s[1:] while s[-1:] == ' ': s = s[:-1] if s == '' or s == ' ': return '' return s 正解2:

def trim(s): if s[:1] == ' ': s = trim(s[1:]) if s[-1:] == ' ': s = trim(s[:-1]) return s 容易写错的方法: def trim(s): while s[0] == ' ': s = s[1:] while s[-1] == ' ': s = s[:-1] return s 解释:(当s=''时,s[0]和s[-1]会报IndexError: string index out of range,但是s[:1])和s[-1:]不会。

s='' s[0] Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> s[0] IndexError: string index out of range s[:1] '' s[1:] '' s[-1] Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> s[-1] IndexError: string index out of range

Barnett007

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

这样也是OK的:

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

郑瑞召KK

#3 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-
 def trim(s):
    return s if s[:1]!=' ' and s[-1:]!=' ' else (trim(s[1:]) if s[:1]==' ' else trim(s[:-1]))

大神啊。。。赞一个

Hi Barnett007,

容易写错的方法: def trim(s): while s[0] == ' ': s = s[1:] while s[-1] == ' ': s = s[:-1] return s

当s=''时,s[0]和s[-1]会报IndexError: string index out of range,但是s[:1]和s[-1:]不会

能解释下为什么 s[0]和s[-1] VS s[:1]和s[-1:] 会造成 index的问题吗?

关于这个容易写错的方法我说明下,问题出现在索引超出范围,即当''里面没有空格时,即不是迭代数,也没有所谓的索引,所有会出错

桂兴牛2号

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

这个答案是我看到过的最厉害的答案,太厉害了。逻辑思维太可怕

桂兴牛2号

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

我是说那个只写了一行语句的楼上这位大神

if s == '' or s == ' ': return '' 这句没有必要吧

def trim(s): while s[:1] == ' ': s = s[1:] while s[-1:] == ' ': s = s[:-1] return s


  • 1

Reply