您的位置:首页 > 编程语言 > Python开发

实验一下Python中初级的方法

2008-08-27 20:12 411 查看
再次好好看看Python,看看里边初级的方法如print等,以及三个内建类型list,tuple,dictionary,以及内建方法slice等的操作,虽然都是很基础的东西,但是记录下来,以后可以复习巩固.
_str = "Hello, Python!"
print "_str's length = ", len(_str)
_list = [1, 2, 3]
print "_list's length = ", len(_list)
_tuple = tuple(_str)
print "_tuple's length = ", len(_tuple)
#max() & min()
print "Max(_list) = ", max(_list) #result:3
print "Min(_list) = ", min(_list) #result:1
#slice a list
_list_slice = _list[1:3]
print "Members in _list_slice:";
for _ls in _list_slice: #result:2 3.Begin form index 1, end before index 3
print _ls
#modify a list using 'slice'
_list[1:4] = [6, 4, 10]
print "Members in new list:";
for _ls in _list: #result:1 6 4 10.Length changed to 4
print _ls
#get tuple elements
print "Members in _tuple:";
for _t in _tuple: #result:Hello, Python!(over).Each char a line.
print _t
#slice a tuple
_tuple_slice = _tuple[:-1]
print "Members in _tuple_slice:";
for _ts in _tuple_slice: #result: H e l l o , [space] P y t h o n(over).End before the last one.All char in a line as a result of '//'.(maybe ",")
print _ts, /
#must go on in the next line, otherwise a "invalid syntax" error. comment or null line is help.
#however, if no "/" last line, just end with ",", we can use "print" just after last line, with content in the same line if no "/n"
print "/nhello"
#dictionary
_dic = { 'i' : 'u',
'he' : 'she'}
_dic['him'] = 'her' #add an element him->her
_dic[9] = 'I am' #add an element 9->I am
print "_dic's length = " , len(_dic)
for _key in _dic: #result: as in _dic, not as the order
print _key, "/t:/t", _dic[_key]
#usage of "print"
print "It's %d bug, maybe!" % 1 #result: it's 1 bug, maybe!
print ("not like %s and %s" % ('C', 'C++')) #result: not like c and c++
#modify tuple
try:
_tuple[1] = 'r' #raise an error
except TypeError:
print "Tuple object can't be modified"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: