掉了个坑
Topic source这样也是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
# -*- 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的问题吗?
- 1
Barnett007
正解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:]不会。