Python学习笔记(6)
2013-09-29
627
简介:
Python学习笔记(6)
1)SequenceSequence是一对象,一个接一个地保存多种数据项。Python中Sequence有几种不同类型。下面先看两种Sequence基本类型:字符串和列表在字符串中访问单个字符:用for循环迭代字符串,语法如下:for variable in string: statement statement etc.
Python学习笔记(6)
1)SequenceSequence是一对象,一个接一个地保存多种数据项。Python中Sequence有几种不同类型。下面先看两种Sequence基本类型:字符串和列表在字符串中访问单个字符:用for循环迭代字符串,语法如下:for variable in string: statement statement etc.例子:>>> name = 'Juliet'>>> for ch in name: print chJulie例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还可以用负数做序号,-1表示字符串最后一个字符,-2表示倒数第2个字符,依次类推。>>> my_string[-1]'d'>>> my_string[-2]'e'序号错误序号有范围,如‘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字符串分割格式如下:string[start:end]例:>>> full_name = 'Patty Lynn Smith'>>> middle_name = full_name[6:10]>>> print middle_nameLynn例: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_nameP14.pyimport logindef 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()测试子串是否在字符串中用in 或 not in列表的方法append(item) 在列表最后添加itemindex(item) 返回序号指定的元素insert(index, item) 在指定序号后插入itemsort() 列表按从小到大的顺序排序remove(item) 删除列表中第一个出现item的项reverse() 列表反序例:>>> my_list = [1,2,3,4,5]>>> del my_list[2]>>> print my_list[1, 2, 4, 5]>>> 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
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。