python字符串、元祖、列表(有代码有注释)

xiaoxiao2021-02-27  138

通过直接运行代码看结果,体会一下python基本数据类型的用法。 请注意看代码注释。   ======python代码开始======

 

print '\n======="字符串"操作=======' # 对字符串乘以N, 表示此字符串重复N次 print "==" *10 s1 = "hello \r" # \r是python里的回车符 s2 = r"hello \r" # r"xxxxx" 原样输出双引号里的内容 s3 = "你好" s4 = u"你好" print s1 print s2 print type(s3),s3 #str型 print type(s4),s4 #unicode型 # 字符串切片 string = "Tony_仔仔" print "'Tony_仔仔'的前4个字:\t",string[:4] print "生成泪奔表情:\t", string[0]+string[4]+string[0] print "\n=======(元祖)操作=======" """ 定义一个元祖序列. 元祖特性是:一旦定义就不可变,即不再允许改变元祖本身或元祖内的元素! 元祖,字符串,列表都属于序列. 序列特性:有序的, 能按照下标范围操作序列中的元素(此操作也成为切片操作) """ tp = (1, 2, 3, 4, 5, "abcde", "hello") print tp[1:] # 切片操作: 从下标1切到最后一个元素 print tp[1:len(tp)] print tp[:-2] # 切片规则: 下标以0开始; 包含开始下标,不包含结束下标 print "reverse tuple with step of 3: ",tp[::-3] print "reverse tuple with step of 1: ", tp[::-1] print "\n=======列表操作=======" # 把元祖类型强制转行成列表类型 a_list= list(tp) if type(a_list) == type([1,2,3]): # 若是列表类型则打印 print (a_list) print"遍历列表:" for e in a_list: print e, # 加逗号表示不换行打印 b_list = (a_list) print "\n b_list所有元素:\t",b_list print "before del b_list[1]:\t", b_list del b_list[1] # python 3.X可以删除列表中的元素,python 2.x不支持 print "after del b_list[1]:\t",b_list print "'hello' first index in b_list: ",b_list.index("hello") # 返回指定元素的第一次出现的索引 print "after del b_list[b_list]:\t", b_list tp2 = (0,"tony"), (1, "kid"), (2, "kid") b = dict(tp2) if type(b) == type({"a":10}): print b # tp2_2 = reversed(tp2) tp2_3 = tp2[::-1] for e in tp2_3: print e, # 与tp2_2的结果一样

 

 

======python代码结束======

 

代码运行结果: ======="字符串"操作======= ==================== hello  hello \r <type 'str'> 你好 <type 'unicode'> 你好 'Tony_仔仔'的前4个字: Tony 生成泪奔表情: T_T =======(元祖)操作======= (2, 3, 4, 5, 'abcde', 'hello') (2, 3, 4, 5, 'abcde', 'hello') (1, 2, 3, 4, 5) reverse tuple with step of 3:  ('hello', 4, 1) reverse tuple with step of 1:  ('hello', 'abcde', 5, 4, 3, 2, 1) =======列表操作======= [1, 2, 3, 4, 5, 'abcde', 'hello'] 遍历列表: 1 2 3 4 5 abcde hello  b_list所有元素: [1, 2, 3, 4, 5, 'abcde', 'hello'] before del b_list[1]: [1, 2, 3, 4, 5, 'abcde', 'hello'] after del b_list[1]: [1, 3, 4, 5, 'abcde', 'hello'] 'hello' first index in b_list: 5 after del b_list[b_list]: [1, 3, 4, 5, 'abcde', 'hello'] {0: 'tony', 1: 'kid', 2: 'kid'} (2, 'kid') (1, 'kid') (0, 'tony') 

 

转载请注明原文地址: https://www.6miu.com/read-12566.html

最新回复(0)