python基础之--列表,元组,字典,字符串操作
一. 列表(list)
(1)创建
list = ['1',(1,2),'1', '2']
(2) 得到list 长度
>>> print len(list)
4
(3) 删除
>>> del list[0]
>>> print list
[(1, 2), '1', '2']
>>> del list[0:2]
>>> print list
['2']
(4) 添加
>>> list.append('3')
>>> print list
['2', '3']
(5) 插入
>>> list[0:0] = ['sample value']
>>> print list
['sample value', '2', '3']
>>> list[0:0] = ['sample value', 'sample value 1']
>>> print list
['sample value', 'sample value 1', 'sample value', '2', '3']
>>> list[1:2] = ['sample value 2', 'sample value 3']
>>> print list
['sample value', 'sample value 2', 'sample value 3', 'sample value', '2', '3']
(6) 取值,遍历
取值单个值
>>> print list[0]
sample value
>>> print list[1]
sample value 2
>>> print list[2]
sample value 3
取片段
>>> print list[2:4]
['sample value 3', 'sample value']
遍历
>>> for line in list:
... print line
...
sample value
sample value 2
sample value 3
sample value
2
3
list的其他方法:
L.append(var) #追加元素
L.insert(index,var)
L.pop(var) #返回最后一个元素,并从list中删除之
L.remove(var) #删除第一次出现的该元素
L.count(var) #该元素在列表中出现的个数
L.index(var) #该元素的位置,无则抛异常
L.extend(list) #追加list,即合并list到L上
L.sort() #排序
L.reverse() #倒序
二. 元组(tuple)
#元组和列表十分类似,只不过元组的元素是不可改变的,相当于只读列表
tuple = ('a', 'b', 'c', 'd', 'e')
>>> print tuple[0]
a
>>> print tuple[0:2]
('a', 'b')
三. 字典(dict)
key-value的数据结构.
#创建字典:
(1)基本
d = {} #空字典
d = {'name':'tom', 'age':22}
#等价
d = {}
d['name'] = 'tom'
d['age'] = 22
(2)dict
d = dict() #空
d = dict(name='tom', age=22)
d = dict([('name','tom'), ('age',22)])
#等价
keys = ['name','age']
values = ['tom', 22]
d = dict(zip(keys,values))
(3) fromkeys
>>> dict.fromkeys(['name','age'],'default_value')
{'age': 'default_value', 'name': 'default_value'}
#判断key是否存在
if k in d: #k not in
dosomething()
#读取
print d['name'] #存在得到结果,但是若键不存在,将引发异常KeyError。建议不使用
print d.get('name', 'jack') #存在得到,若键不存在,返回第二个参数default_value.若是没有设default_value返回None
#使用用例
if k in d:
print d[k]
try:
print d[k]
except KeyError:
dosomething()
print d.get(k, default)
#等价 d[k] if k in d else default
#遍历
for key in d:
print key, d[key]
#等价 for key in d.keys()
for key,value in d.items():
print key, value
#修改
d['name'] = 'tom'
d.update({'name':'tom'}) #这里支持一整组值
d.update( [ ('name','tom'), ('age',2) ] ) #每个元组两个元素,(key,value)
d.update('name'='tom', 'age'=4)
#删除
del d['key']
value = d.pop('key') #删除并返回值
d.clear() #清空
#排序
d = {'a':10, 'c':8, 'b':9, 'd':7}
#1)字典排序 按照key排序
keys = d.keys()
keys.sort()
for key in keys:
print d.get(key)
结果为:
10
9
8
7
(2) 按照value进行排序
sorted(d.items(), lambda x,y: cmp(x[1],y[1]))
结果为:
[('d', 7), ('c', 8), ('b', 9), ('a', 10)]
(3) 另一种排序方法
sorted(d)
>>> print d
{'a': 10, 'c': 8, 'b': 9, 'd': 7}
#其他
dictionary的方法
D.get(key, 0) #同dict[key],多了个没有则返回缺省值,0。[]没有则抛异常
D.has_key(key) #有该键返回TRUE,否则FALSE
D.keys() #返回字典键的列表
D.values() #以列表的形式返回字典中的值,返回值的列表中可包含重复元素
D.items() #将所有的字典项以列表方式返回,这些列表中的每一项都来自于(键,值),但是项在返回时并没有特殊的顺序
D.update(dict2) #增加合并字典
D.popitem() #得到一个pair,并从字典中删除它。已空则抛异常
D.clear() #清空字典,同del dict
D.copy() #拷贝字典
D.cmp(dict1,dict2) #比较字典,(优先级为元素个数、键大小、键值大小)
#第一个大返回1,小返回-1,一样返回0
dictionary的复制
dict1 = dict #别名
dict2=dict.copy() #克隆,即另一个拷贝。
四. 字符串(string)
判断 – 通常返回一个bool值
str.isalpha() 是否只包含文字
str.isdecimal() 是否只包含数字(多语言数字)
str.isdigit() 是否只包含数字(0~9)
str.isnumeric() 是否只包含数字字符
str.isalnum() 是否只包含文字和数字
str.isidentifier() 是否是合法标识符
str.islower() 是否是小写
str.isupper() 是否全是大写
str.istitle() 是否每词首字母大写
str.isprintable() 是否只包含可打印字符
str.isspace() 是否只包含空白字符
str.startswith(prefix[, start[, end]]) 是否以prefix开头
str.endswith(suffix[, start[, end]]) 是否以suffix结尾
修饰 – 通常返回一个修饰后的字符串
str.capitalize() 返回一个首字母大写的字符串
str.title() 返回每个词首字母大写的字符串
str.expandtabs([tabsize]) "\t"转换成空格
str.upper() 全转换成大写
str.lower() 全转换成小写
str.ljust(width[, fillchar]) 左对齐,右填充
str.rjust(width[, fillchar]) 右对齐,左填充
str.center(width[, fillchar]) 居中,两边填充
str.lstrip([chars]) 去除左空白或自定字符
str.rstrip([chars]) 去除右空白或自定字符
str.strip([chars]) 去除两边空白或自定字符
str.swapcase() 大小写互转
str.zfill(width) 左侧填充0到指定宽,一般用来修饰数字
查找&&替换
str.count(sub[, start[, end]]) 计算[start, end)间,sub出现次数
str.find(sub[, start[, end]])
str.index(sub[, start[, end]])
str.rfind(sub[, start[, end]])
str.rindex(sub[, start[, end]])
str.replace(old, new[, count])
拆分&&组合
str.join(iterable)
str.partition(sep)
str.rpartition(sep)
str.split([sep[, maxsplit]])
str.rsplit([sep[, maxsplit]])
str.splitlines([keepends])
转换
hex(x)
int([number | string[, base]])
len(s)
list([iterable])
oct(x)
ord(c)
repr(object)
reversed(seq)
str([object[, encoding[, errors]]])
字符串的格式化:
str_format % (参数列表) #参数列表是以tuple的形式定义的,即不可运行中改变
>>>print ""%s's weight is %dKG" % ("My teacher", 70)
#结果显示为 My teacher's weight is 70KG