2-python代码坑点
Posted ystraw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2-python代码坑点相关的知识,希望对你有一定的参考价值。
#切片: # L = [‘aaa‘, ‘bbb‘, ‘ccc‘, ‘ddd‘] # print(L[1 : 3]) #取[1, 3):下标 # L = list(range(100)) # print(L[:10]) # print(L[-10:]) # # print(L[2:10:4]) #从2开始取,步长为4,小于10 # # [2, 6] # print(‘abcdefg‘[:3]) # # abc # print(‘abcdefg‘[::2]) # # aceg #取出字符串的首位空格的函数 # def trim(s): # if s == ‘‘: # return ‘‘ # len1 = len(s) # i = 0 # j = len1 - 1 # while i < len1 and s[i] == ‘ ‘: # i += 1 # print(i) # while j > 0 and s[j] == ‘ ‘ : # j -= 1 # print(j) # if i <= j: # print(i, (j)) # return s[i:j+1] # else: # return ‘‘ #递归写法: # def trim(s): # if s == ‘‘: # return s # if s[:1] == ‘ ‘: # # if s[0] == ‘ ‘: # return trim(s[1:]) # if s[-1:] == ‘ ‘: # # if s[-1] == ‘ ‘: # return trim(s[:-2]) # else: # return s #递归写法2: def trim(s): if s == ‘‘: return s if s[0] == ‘ ‘: s = trim(s[1: ]) #如果这里不用返回值的话,必须要在下面判空,否则可能s已经为空了,再去做下一个if判断,就会越界 # return trim(s[1: ]) if s == ‘‘: return s if s[-1] == ‘ ‘: s = trim(s[ :-2]) # return trim(s[ :-2]) return s # # # 测试: t = [1, 2, 3, 4, 5] print(t[:-2]) if trim(‘ ‘) != ‘‘: print(‘ys‘ + trim(‘ hello‘) + ‘ys‘) print(‘no‘) # if trim(‘hello ‘) != ‘hello‘: print(‘a‘ + trim(‘hello ‘) + ‘b‘) print(‘1测试失败!‘) elif trim(‘ hello‘) != ‘hello‘: print(‘2测试失败!‘) elif trim(‘ hello ‘) != ‘hello‘: print(‘3测试失败!‘) elif trim(‘ hello world ‘) != ‘hello world‘: print(‘4测试失败!‘) elif trim(‘‘) != ‘‘: print(‘5测试失败!‘) elif trim(‘ ‘) != ‘‘: print(‘6测试失败!‘) else: print(‘测试成功!‘)
以上是关于2-python代码坑点的主要内容,如果未能解决你的问题,请参考以下文章
Numpy解决:关于 dtype=object 的含义及坑点
聊一聊新建项目eslint报错Expected linebreaks to be ‘LF‘ but found ‘CRLF‘ 的坑点
聊一聊新建项目eslint报错Expected linebreaks to be ‘LF‘ but found ‘CRLF‘ 的坑点
聊一聊新建项目eslint报错Expected linebreaks to be ‘LF‘ but found ‘CRLF‘ 的坑点