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

来源:互联网 发布:nginx 图片服务器配置 编辑:程序博客网 时间:2024/05/10 01:18
通过直接运行代码看结果,体会一下python基本数据类型的用法。
请注意看代码注释。
======python代码开始======

print '\n======="字符串"操作======='# 对字符串乘以N, 表示此字符串重复N次print "==" *10s1 = "hello \r"  # \r是python里的回车符s2 = r"hello \r"  # r"xxxxx" 原样输出双引号里的内容s3 = "你好"s4 = u"你好"print s1print s2print 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_listprint "before del b_list[1]:\t", b_listdel b_list[1]  # python 3.X可以删除列表中的元素,python 2.x不支持print "after del b_list[1]:\t",b_listprint "'hello' first index in b_list: ",b_list.index("hello")  # 返回指定元素的第一次出现的索引print "after del b_list[b_list]:\t", b_listtp2 = (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: 5after del b_list[b_list]:[1, 3, 4, 5, 'abcde', 'hello']{0: 'tony', 1: 'kid', 2: 'kid'}(2, 'kid') (1, 'kid') (0, 'tony') 

0 0