python學習筆記1 切片

2021-08-15 19:06:35 字數 1148 閱讀 4321

本著資源共享的原則,這是我自學的成品,望各位大佬指正。

1 利用切片操作完成以下內容

去除字串首尾的空格

#**如下:

l = "    hello "

l2 = "hello "

print('元')

print(l)

##print(l[0:3])

# -*- coding: utf-8 -*-

def trim(s):

## print('進入')

for i in s:

if s[0] == ' ':

s = s[1:len(s)]

#print(s)

else:

break

for i in s:

if s[len(s)-1] == ' ':

s = s[0:len(s)-1]

else:

break

## return [s,len(s)]

return s

#l = l[1:len(l)]

#trim(l)

print(trim(l))

#print('len')

#print(len(trim(l)))

#print(l2)

### 測試:

##if trim('hello ') != 'hello':

## print('測試失敗!')

##elif trim(' hello') != 'hello':

## print('測試失敗!')

##elif trim(' hello ') != 'hello':

## print('測試失敗!')

##elif trim(' hello world ') != 'hello world':

## print('測試失敗!')

##elif trim('') != '':

## print('測試失敗!')

##elif trim(' ') != '':

## print('測試失敗!')

##else:

## print('測試成功!')

Python學習筆記 切片

學習廖雪峰python教程所得。1.切片 slice 可用於list tuple或字串。以list為例 l a b c d e 切片操作符 l x y z x y z 切片索引,x是左端,y是右端,z是步長,在 x,y 區間從左到右每隔z取值,預設z為1可以省略z引數。步長的負號就是反向,從右到左取...

Python學習筆記 切片操作

slice start stop step 0 represent the left end of the sequence,1 represents the right end of the sequence.mystring my string if the sign of the step i...

Python 學習筆記 4 1 切片

取乙個list或tuple的部分元素是非常常見的操作。比如,乙個list如下 l michael sarah tracy bob jack 取前3個元素,應該怎麼做?笨辦法 l 0 l 1 l 2 michael sarah tracy 之所以是笨辦法是因為擴充套件一下,取前n個元素就沒轍了。取前n...