九州体育网 - 十年信誉网站

关于作者

Discuss / Python / 完成

完成

Topic source

小浣熊悳乾脆面

#1 Created at ...

def trim(sstr): strlen = len(sstr) if strlen==0: return '' n=0 i=-1 while sstr[n]==' ': n=n+1 if n==strlen: return '' while sstr[i]==' ': i=i-1 i=i+1 if i ==0: return sstr[n:] elif i!=0: return sstr[n:i]

小浣熊悳乾脆面

#2 Created at ...

看了大家的,感觉自己写的好麻烦啊,还是需要多多学习才行

xlzbitichong

#3 Created at ...

代码少并总是好事,你这种写法效果更高

import time

def trim(s): length = len(s) if length == 0: return s

n = 0
while n < length:
    if s[n] == ' ':
        n = n + 1
    else:
        break

if n == length - 1:
    return ''

m = 0
while m < length - 1:
    if s[-(m + 1)] == ' ':
        m = m + 1
    else:
        break

return s[n:length - m]

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

testCount = 1000000

t1 = time.time() i = 0 while i < testCount: trim(" uuuuuuuu uuuuuuuu ") i = i + 1

t2 = time.time() i = 0 while i < testCount: trim2(" uuuuuuuu uuuuuuuu ") i = i + 1

t3 = time.time()

print(t2 - t1, t3 - t2)


  • 1

Reply

WARNING: You are using an old browser that does not support HTML5. Please choose a modern browser (Chrome / Microsoft Edge / Firefox / Sarafi) to get a good experience.