首页 > 编程语言 >极客编程python入门-切片

极客编程python入门-切片

时间:2022-11-22 10:10:26浏览次数:34  
标签:trim 10 elif 极客 python 编程 切片 print hello


切片


取一个list或tuple的部分元素是非常常见的操作。


>>> L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
>>> [L[0], L[1], L[2]]
['Michael', 'Sarah', 'Tracy']


Python提供了切片(Slice)操作符,能大大简化这种操作


>>> L[0:3]
['Michael', 'Sarah', 'Tracy']


切片操作十分有用。我们先创建一个0-99的数列:


>>> L = list(range(100))
>>> L
[0, 1, 2, 3, ..., 99]


可以通过切片轻松取出某一段数列。


>>> L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


后10个数:


>>> L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]


前11-20个数:


>>> L[10:20]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]


所有数,每5个取一个:


>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]


甚至什么都不写,只写[:]就可以原样复制一个list:


>>> L[:]
[0, 1, 2, 3, ..., 99]


tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple:


>>> (0, 1, 2, 3, 4, 5)[:3]
(0, 1, 2)


字符串'xxx'也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串:


>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[::2]
'ACEG'


极客编程python入门-切片_切片


练习


利用切片操作,实现一个trim()函数,去除字符串首尾的空格


def trim(s):

if len(s) == 0:

return s

else:

while s[0] == ' ':

s = s[1:]

if len(s) == 0:

return s

while s[-1] == ' ':

s = s[:-1]

if len(s) == 0:

return s

return s

# 测试:
if trim('hello ') != 'hello':
print('01测试失败!')
elif trim(' hello') != 'hello':
print('02测试失败!')
elif trim(' hello ') != 'hello':
print('03测试失败!')
elif trim(' hello world ') != 'hello world':
print('04测试失败!')
elif trim('') != '':
print('05测试失败!')
elif trim(' ') != '':
print('06测试失败!')
else:
print('测试成功!')


极客编程python入门-切片_切片_02


标签:trim,10,elif,极客,python,编程,切片,print,hello
From: https://blog.51cto.com/apple0/5876274

相关文章