1)Sequence Sequence是一对象,一个接一个地保存多种数据项。Python中Sequence有几种不同类型。 下面先看两种Sequence基本类型:字符串和列表 在字符串中访问单个字符: 用for循环迭代字符串,语法如下: for variable in string: statement statement etc. 例子: >>> name = 'Juliet' >>> for ch in name: print ch J u l i e
例2: # This program counts the number times # the letter T appears in a string. def main(): count = 0 my_string = raw_input('Enter a sentence: ') for ch in my_string: if ch == 'T' or ch == 't': count +=1 print 'The letter T appears',count,'times.' main()
使用索引访问字符串中的单个字符 字符串的每个字符都有一个序号,表示它在字符串中的位置。 例: >>> my_string = 'Roses are red' >>> ch = my_string[6] >>> ch 'a' >>> print my_string[0],my_string[6],my_string[10] R a r
序号错误 序号有范围,如‘Boston’字符串的序号为0~5以及-1~-6。超出此范围则IndexError。 例: >>> city='Boston' >>> print city[6] Traceback (most recent call last): File "", line 1, in print city[6] IndexError: string index out of range
例: login.py # The get_login_name function accepts a first name, # last name, and ID number as arguments. It returns # a system login name. def get_login_name(first,last,idnumber): # Get the first three letters of the first name. # If the name is less than 3 characters, the # slice will return the entire first name. set1 = first[0:3] # Get the first three letters of the last name. # If the name is less than 3 characters, the # slice will return the entire last name. set2 = last[0:3] # Get the last three characters of the student ID. # If the ID number is less than 3 characters, the # slice will return the entire ID number. set3 = idnumber[-3:] # Put the sets of characters together. login_name = set1+set2+set3 return login_name
P14.py import login def main(): first = raw_input('Enter your first name: ') last = raw_input('Enter your last name: ') idnumber = raw_input('Enter your student ID number: ') # Get the login name. print 'Your system login name is:' print login.get_login_name(first, last, idnumber) main()
>>> my_list=[5,4,3,123,50,40,30] >>> print 'The lowest value is',min(my_list) The lowest value is 3 >>> print 'The highest value is', max(my_list) The highest value is 123