Discuss / Python / 看了你们很多的答案,你们干嘛还要用循环,廖老师说切片是用来减少循环的操作的!

看了你们很多的答案,你们干嘛还要用循环,廖老师说切片是用来减少循环的操作的!

Topic source

biggerdream

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

所以,我选择递归

def trim(s):

#去掉前面的空格
if s[:1] == ' ':
    return trim(s[1:])

#去掉后面的空格
if s[-1:] == ' ':
    return trim(s[:-1])

return s

Bugs___Bunny

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

n=0 a="A" while n<10000: a=" "+a n=n+1 print(trim(a))

何小狗____

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

仁兄你的写得好好

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

和我写的最终版本一样。最精简

怼怼君

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

def trim(s): if s[:1] == ' ': s = trim(s[1:]) elif s[-1:] == ' ': s = trim(s[:-1])

return s

  • 1

Reply