0.序列
列表,元组,字符串都是序列。
序列有两个特点:索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。
以字符串为例:
1 str="01 3456 89?" 2 3 print( str[0] ) #‘0‘,索引 4 print( str[1:5] ) #‘1 34 ‘,切片 5 print( str[5:1:-1] ) #‘543 ‘ 6 print( str[1:5:-1] ) #output a ‘\n‘,no error
1.列表
列表的常见操作:
1 fruitList = [‘lemon‘, ‘mango‘] 2 print( len(fruitList),"kinds of fruit" ) #2 kinds of fruit 3 4 for fruit in fruitList: 5 print( fruit ) 6 7 fruitList.append( "banana" ) #fruitList = [‘lemon‘, ‘mango‘, ‘banana‘] 8 del fruitList[0] #fruitList = [‘mango‘, ‘banana‘] 9 fruitList[0]=‘orange‘ #fruitList = [‘orange‘, ‘mango‘] 10 fruitList.sort() #fruitList = [‘banana‘, ‘orange‘] 11 fruitList.remove(‘banana‘) #fruitList = [‘orange‘]
当然你也可以这么玩儿:
1 special_list = ["str", 1, ("tupleA",2), [3,4,5] ] 2 print(special_list[2][0]) #tupleA 3 print(special_list[3][2]) #5
2.元组
元组和列表十分类似,只不过元组和字符串一样是不可变的。即你不能修改元组。元组的初始化方式如下:
1 fruitTuple = (‘lemon‘, ‘mango‘) 2 emptyTuple = () #empty tuple 3 oneElementTuple = (1,) #tuple has only one element
注意初始化一个元素的元组时,需要在唯一元素后带逗号,表示当前初始化的是一个元组而不是带括号的对象。
常用于打印语句中,和%合作实现定制字符串输出。
3.字符串
字符串常见操作:
1 smile = "~^_^~" 2 if smile.startswith("@[email protected]"): 3 print("it is fake smile") 4 if "~" in smile: 5 print("you may be shy") 6 if smile.find("?") != -1: 7 print("are you confused?") 8 9 alist = ["1","2","3"] 10 joinStr = smile.join(alist) #joinStr = ‘1~^_^~2~^_^~3‘ 11 splitList = joinStr.split(‘~‘) #splitList = [‘1‘, ‘^_^‘, ‘2‘, ‘^_^‘, ‘3‘]
时间: 2024-10-12 20:38:17