实例学习pythonzifuchuan/ target=_blank class=infotextkey>python字符串、元组、列表等用法。
复制代码 代码示例:
#格式化字符串
a = "%d and %d" % (-1,2);
b = "%s's height is %dcm"%("Charles",180);
print a;
print b;
#其他格式化字符串0
a = " abcdef ";
print len(a);#原始长度
print len(a.lstrip());#去掉左边空白
print len(a.rstrip());#去掉右边空白
print len(a.strip());#去掉两边空白
9
8
7
6
#输出中文
s="中文"
print s.decode('utf-8').encode('gb2312')
#合并(join)
word = ["aaa", "bbbb", "ccccc"];
a = "##".join(word);
print a;# aaa##bbbb##ccccc
#分解(split)
word = "aaa##bbbb##ccccc";
a = word.split("##");
print a;# ['aaa', 'bbbb', 'ccccc']
#元组相当于java的常量,不可变
a = (1, 2, 3, 4);
b, c = (1, 2);
print a;
print b;
#序列(sequence)##
#1、in 判断sequenue是否包含某字符串
a = "please call me ck";
print "ck" in a;
#2、“*”号表示重复
a = "a" * 3;
b = "12" * 3;
print a; #aaa
print b; #121212
#字典,相当于java的map
mymap = {"name": "ck", "age": 25};
print mymap["name"]; #ck
print mymap["age"]; #25
#dict(L)生成一个字典, L为一个List, List中每一个元素都是tuple数组
mymap = dict([("name", "ck"),("age", 25)]);
print mymap; #{'age': 25, 'name': 'ck'}
print mymap["name"]; #ck
print mymap["age"]; #25
#mymap = dict([("name" + str(x),10*x) for x in [1,2,3]]);
print mymap; #{'name2': 20, 'name3': 30, 'name1': 10}
#mymap = {"name": "ck", "age": 25};
mymap["sex"] = "male"; #增加一个元素
print mymap; #{'age': 25, 'name': 'ck', 'sex': 'male'}
#dictionary 取元素的另一种方法,跟java类似
mymap = {"name": "ck", "age": 25};
print mymap.get("age"); #25
print mymap.get("address", "default") #default
#dictionary 判断是否包含key
mymap = {"name": "ck", "age": 25};
print mymap.has_key("name"); #True
print mymap.has_key("address"); #False
#dictionary 得到所有的key, 和所有的value
mymap = {"name": "ck", "age": 25};
print mymap.keys(); #['age', 'name']
print mymap.values(); #[25, 'ck']
#dictionary 遍历字典
for k in mymap.keys():
print k + ":" + str(mymap[k]);
#程序流程##
#if判断,除None、0、""(?空字符串)、[](?list)、{}(dictionary )、()(?tuple)外,其他都是真
a = 5;
if a == 1: print 1;
elif a == 2: print 2;
else: print 3;
#for循环
for k in (1,2,3): print k;
#while 循环
i = 1;
while i < 4:
print i; i = i + 1;
else:
print "else";
1
2
3
else