切片就是list取值的一种方式,
l = list(range(5))
print(l)
# [0, 1, 2, 3, 4] 循环5次
--------------------------------------------------------------------------------
l = list(range(1,11))
print(l)
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 从1开始,到10
--------------------------------------------------------------------------------
l = ['a','b','c','d','e','j','k','l','m','n','o']
print(l[2:8])#顾头不顾尾 ['c', 'd', 'e', 'j', 'k', 'l']
print(l[:5])#如果最前面没写的话,代表从0开始取的 ['a', 'b', 'c', 'd', 'e']
print(l[4:])#如果冒号后面的没写的话,代表取到最后 ['e', 'j', 'k', 'l', 'm', 'n', 'o']
print(l[:])#如果冒号后面的没写的话,代表取到最后 ['a', 'b', 'c', 'd', 'e', 'j', 'k', 'l', 'm', 'n', 'o']
print(l[::3])#步长,也就是代表隔几个取一次 ['a', 'd', 'k', 'n']
--------------------------------------------------------------------------------
nums = list(range(1,101))
print(nums[1::2]) #取偶数
#[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
print(nums[::2]) #取奇数
#[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
print(nums[::-1]) #倒序
#[100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(nums[::-2]) #倒序取偶数
#[100, 98, 96, 94, 92, 90, 88, 86, 84, 82, 80, 78, 76, 74, 72, 70, 68, 66, 64, 62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2]
#如果最后面的步长是正数的话,那就从左到右开始取值
#如果后面的步长是负数的话,那就从右往左开始取值
--------------------------------------------------------------------------------
切片同样适用于字符串。
words='中秋节要上课'
# print(words[::-1]) # 课上要节秋中
for index,w in enumerate(words):
print('每次打印的',index,w)
# 每次打印的 0 中
# 每次打印的 1 秋
# 每次打印的 2 节
# 每次打印的 3 要
# 每次打印的 4 上
# 每次打印的 5 课
--------------------------------------------------------------------------------
回文算法,反过来倒去过都一样,比如:上海自来水来自海上;1232321;1111
下面程序判断是否是回文
for i in range(10):
s = input('请输入一个字符串:')
if len(s)<2:
print('字符串长度必须大于1')
elif s==s[::-1]: #字符串没有reverse,列表才有
print('是回文')
else:
print('不是回文')