Discuss / Python / 循环切片/循环list方法

循环切片/循环list方法

Topic source

阳光漫射

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

使用切片操作(看了看网友贴的答案,还是递归函数简单): def trim(s): if s=='': return s else: x=0 y=0 i=0 while s[i]==' ': x=i+1 i=i+1 if i>=len(s): break i=0 while s[len(s)-1-i]==' ': y=i+1 i=i+1 if i>=len(s): break return s[x:len(s)-y]

不使用切片操作(利用list读取字符,最后转str格式输出): def trim(s): a=[] n=len(s) for i in range(n): if s[i]!=' ': a.append(s[i]) return ''.join(a)


  • 1

Reply