Discuss / Python / 贴一下我的代码,没想到和前排的一样

贴一下我的代码,没想到和前排的一样

Topic source

MingkaiNVM

#1 Created at ... [Delete] [Delete and Lock User]
def trim(s):
    if [x for x in s if x is not ' '] is not True:
        raise TypeError
    while s[0] is ' ':
        s = s[1:]
    while s[-1] is ' ':
        s = s[:-1]
    return s

MingkaiNVM

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

第二行错了,改为 if bool([x for x in s if x is not ' ']) is not True:

def trim(s): n=0 m=len(s) for i in range(len(s)): if s[i]!=' ': n=i break for l in range(len(s)): if s[-l-1]!=' ': m=len(s)-l break return s[n:m]

大家能不能帮我看下为啥这个不行?老是通不过。

老哥稳002

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

第二行没看懂,是判断字符串里面有没有空格吗? is not True 为什么不直接写is Flase呢

老哥稳002

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

三楼的代码,你的i和l最大值只能到len(s)-1,而且你用for循环是遍历整个字符串,记下最后一个空格的位置,如果你想分别记下前后两端的最后一个空格的位置的话,可以用while循环。还有你前面已经把m=len(s)了,后面为啥不直接用m呢。

“if bool([x for x in s if x is not ' ']) is not True:”这段代码我没有看懂啊,尤其是[x for x in s if x is not ' ']这一块,我是真没懂,求大神讲解


  • 1

Reply