码迷,mamicode.com
首页 > 编程语言 > 详细

Python---切片

时间:2017-08-03 20:28:31      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:python 切片 slice tuple str

# 切片

L = [‘Michael‘, ‘Sarah‘, ‘Tracy‘, ‘Bob‘, ‘Jack‘]

# 用循环取前3个元素
r = []
n = 3
for i in range(n):
    r.append(L[i])
print(‘get pre 3 elements from L by loop:‘, r)

# 对这种经常取指定索引范围的操作,用循环十分繁琐,因此,Python提供了Slice操作符,简化这种操作
# 用Slice取前3个元素
print(‘get pre 3 elements form L by Slice:‘, L[0:3], L[:3])

# 倒数切片
# 倒数第一个元素的索引是-1
print(L[-2:-1], L[-3:])

# 使用[:]复制一个list
l = L[:]
print(‘copy list L to l, the l is:‘, l)

# 对tuple切片
# 切片的结果是tuple
T = (0, 1, 2, 3, 4, 5, 6, 7, 8)
t = T[:3]
print(‘Slice the tuple T to tuple t, the t is:‘, t)

# 对str切片
# 切片的结果是str
S = ‘ABCDEFG‘
s1 = S[:3]
s2 = S[::2]
print(s1, s2)


Python---切片

标签:python 切片 slice tuple str

原文地址:http://11317783.blog.51cto.com/11307783/1953393

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!