Python—字符串、列表和元组比较

it2022-05-05  147

文章目录

基础比较遍历字符串列表元组 搜索定位字符串分割变换列表翻转排序反转排序

基础比较

\字符串列表元组总结符号表示’ ‘/" "/’’’ ‘’’/""" “”"/[]()特点可作为元素加入到列表或元素中有序、可变、可重复有序、可重复、不可变拼接用+连接用+连接用+连接都可用代码print(a+b)做拼接输出重复用乘号重复用乘号重复用乘号重复都可用代码print(a*n)做重复输出索引/切片[][:][::][] [:][::][][:][::]表示的方式都相同,列表和元组可按照需求进一步索引增join()append()、extend()、insert()不可改变删sr.strip()pop()、remove()、del、clear()不可删单个元素,只能用del删除整个元组改replace()li[x]=’’ 直接更改不可更改,但如果元组中有列表可更改列表中的元素,更改完后元组也会发生改变查find()、index()索引、切片、for循环遍历索引、切片、for循环遍历列表与元组类似计数count()count()count()

遍历

字符串

a="City College " for i in range(len(a)): print(a[i],end=" ") for i in a: print(i,end=" ") print(a[:4])

列表

元素遍历 li=['c','i','t','y','1','9','0','9'] for i in li: print(i)

索引遍历

for i in range(len(li)): print(li[i])

枚举遍历

enumerate() 对于一个可迭代的/可遍历的对象(如列表,字符串等),将其组成一个索引序列,利用它,我们可以同时获得索引和值 li=['c','i','t','y','1','9','0','9'] for i in enumerate(li,2): print(i,end=" ") for index,value in enumerate(li,2): print((index,value),end=' ') # (2, 'c') (3, 'i') (4, 't') (5, 'y') (6, '1') (7, '9') (8, '0') (9, '9')

元组

元素遍历

tp=('c','i','t','y','1','9','0','9') for i in tp: print(i)

索引遍历

tp=('c','i','t','y','1','9','0','9') for i in range(len(tp)): print(tp[i])

枚举enumerate

tp=('c','i','t','y','1','9','0',[1,2,3]) for i in enumerate(tp): print(i,end=' ') # (0, 'c') (1, 'i') (2, 't') (3, 'y') (4, '1') (5, '9') (6, '0') (7, [1, 2, 3])

搜索定位

字符串find()、index()

列表、元组index()

sr = "Life is short, you need python." print(sr.find('e')) print(sr.index('e')) print(sr.rindex('e')) print(sr.replace('I need','I use')) 3 3 21 Life is short, you need python. # 列表、元组 # .index() li = ['d', 'a', 's', 'd', 'a', 's', 'd', 'aa'] tp = ('d', 'a', 's', 'd', 'a', 's', 'd', 'aa') print(li.index('a')) print(li.index('a')) 1 1 --------------------- 作者:Ezio_Auditore777 来源: 原文:https://blog.csdn.net/Ezio_Auditore777/article/details/96439747 版权声明:本文为博主原创文章,转载请附上博文链接!

字符串分割变换

join(),将指定字符插入到元素之间split(),以指定字符分割字符串并去除该字符partition(),以指定字符分割字符串但保留该字符 a="City College" print('+'.join(a)) li=['a','b','c'] print(''.join(li)) print(a.split('e')) print(a.partition('e'))

列表翻转排序

反转

reverse()

li=['c','i','t','y','1','9','0','9'] li.reverse() print(li)

排序

sort()

按照ASCII码值排序

li=['c','i','t','y','1','9','0','9'] li.sort() print(li) li.sort(reverse=True) print(li)

最新回复(0)