Discuss / Python / 如果要使用s[0]或s[-1] 应该避免空字符串时下标越界

如果要使用s[0]或s[-1] 应该避免空字符串时下标越界

Topic source

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


  • 1

Reply