>>> s = 'abcdefg'
#反转操作
>>> s[::-1]
'gfedcba'
#隔一个取一个
>>> s[::2]
'aceg'
>>> 序列类型可用的内建函数
enumerate(iter):接受一个可迭代对象作为参数,返回一个enumerate对象,该对象生成由iter每个元素的index值和item值组成的元组。
用于遍历序列中的元素以及它们的下标:
>>> for i,j in enumerate(('a','b','c')):
print i,j
0 a
1 b
2 creversed(seq):接受一个序列作为参数,返回一个以逆序访问的迭代器。
sorted(iter,func=None,key=None,reverse=False):接受一个可迭代对象作为参数,返回一个有序的列表。
zip(it0,it1...itN):把两个列表对应成对打包。
>>> for i,j in zip(fn,ln):
print ('%s %s' % (i,j)).title() #title方法使第一字母大写
Ian Bairnson
Stuart Elliott
David Paton通过加上None,实现字符串循环递减输出
>>> s = 'abcd'
>>> for i in [None] + range(-1,-len(s),-1):
print s[:i]
abcd
abc
ab
aTemplate属于string中的一个类,可以将字符串的格式固定下来,重复利用。
Template对象有两个方法:substitute()和safe_substitute()
前者更为严谨,key缺少时会报一个KeyError异常,后者缺少key时,直接原封
不动显示字符串。
**************************************************
其主要实现方式为$xxx,其中字符串xxx不能以数字开头
如果$xxx需要和其他字符串接触,可用{}将xxx包裹起来
**************************************************
>>> from string import Template #调用Template
>>> s = Template('There are ${howmany} ${lang} Quotation Symbols')
>>> print s.substitute(lang = 'Python',howmany = 3)
There are 3 Python Quotation Symbols
>>> print s.substitute(lang = 'Python')
Traceback (most recent call last): #报错
File "<pyshell#146>", line 1, in <module>
print s.substitute(lang = 'Python')
File "D:\Python27\lib\string.py", line 172, in substitute
return self.pattern.sub(convert, self.template)
File "D:\Python27\lib\string.py", line 162, in convert
val = mapping[named]
KeyError: 'howmany'
>>> print s.safe_substitute(lang = 'Python')
There are ${howmany} Python Quotation Symbols
>>>
list.append():向列表中添加对象
list.count():返回对象在列表中的出现次数
list.extend():把序列内容添加到列表中
list.insert(index,obj):在索引量为index的位置插入对象obj
list.pop(index = -1):删除并返回指定位置的对象,默认最后一个对象
list.index(obj,i=0,j=len(list)):返回list[k] == obj的k值,并且k的范围在i<=k<j;否则引发ValueError异常
本文介绍了Python中字符串和序列的基本操作方法,包括反转、隔位取值等,并详细讲解了enumerate、reversed、sorted及zip等内置函数的使用方法。此外,还介绍了列表的相关方法及string模块中Template类的应用。
1014

被折叠的 条评论
为什么被折叠?



