1.字符串进行倒序
a='poiuytre'
# 使用字符串切片
reverse_a=a[::-1]
# 使用列表的reverse方法
L=list(a)
L.reverse()
reverse_a=''.join(L)
# 使用reduce
from functools import reduce # reduce函数在python3的内建函数移除了,放入了functools模块
reverse_a = reduce(lambda x,y:y+x,s)
# 使用递归函数
def func(s):
if len(s) <1:
return s
return func(s[1:])+s[0]
reverse_a = func(s)
# 使用栈
def func(s):
L = list(s) #模拟全部入栈
result = ""
while len(L)>0:
result += L.pop() #模拟出栈
return result
reverse_a = func(s)
# for循环
def func(s):
result = ""
max_index = len(s)-1
for index,value in enumerate(s):
result += s[max_index-index]
return result
reverse_a = func(s)
2.求字符串的子集
s='aabasbqwe'
L=[s[i:i+1+x] for x in range(len(s)) for i in range(len(s)-x)]
# 去除重复的子串
S=set(L)
切片:
注意 list = ['a','b','c','d','e'] print(list[10:])输出不会产生IndexError,而是仅仅返回一个空列表,这成为特别让人恶心的疑难杂症,因为运行的时候没有错误产生,导致Bug很难被追踪到。
通常一个切片操作要提供三个参数 [start_index: stop_index: step]
start_index是切片的起始位置
stop_index是切片的结束位置(不包括)
step可以不提供,默认值是1,步长值不能为0,不然会报错ValueError。
当 step 是正数时,以list[start_index]元素位置开始, step做为步长到list[stop_index]元素位置(不包括)为止,从左向右截取。 start_index和stop_index不论是正数还是负数索引还是混用都可以,但是要保证 list[stop_index]元素的【逻辑】位置必须在list[start_index]元素的【逻辑】位置右边,否则取不出元素。
当 step 是负数时,以list[start_index]元素位置开始, step做为步长到list[stop_index]元素位置(不包括)为止,从右向左截取,
start_index和stop_index不论是正数还是负数索引还是混用都可以,但是要保证 list[stop_index]元素的【逻辑】位置
必须在list[start_index]元素的【逻辑】位置左边,否则取不出元素。
一些常用的切片操作:
alist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 取前一部分
alist[:5] # [0,1,2,3,4]
# 取后一部分
alist[-5:] # [5,6,7,8,9]
# 取偶数位置元素
alist[::2] # [0,2,4,6,8]
# 取奇数位置元素
alist[1::2] # [1,3,5,7,9]
# 浅复制,等价于list.copy()更加面向对象的写法
blist = alist[:] # [0,1,2,3,4,5,6,7,8,9]
# 返回一个逆序列表,如果是列表那么推荐reversed(list)的写法,更直观易懂。(字符串没有reverse函数)
alist[::-1] # [9,8,7,6,5,4,3,2,1,0]
# 在某个位置插入多个元素
alist[3:3] = ['a','b','c'] # [0,1,2,'a','b','c',3,4,5,6,7,8,9]
# 在开始位置之前插入多个元素
alist[:0] = ['a','b','c'] # ['a','b','c',0,1,2,3,4,5,6,7,8,9]
# 替换多个元素,注意替换和插入,插入时start=stop,替换时start != stop
alist[0:3] = ['a','b','c'] # ['a','b','c',3,4,5,6,7,8,9]
# 删除切片(字符串没有这个)
del alist[3:6] # [0,1,2,6,7,8,9]