index:
str.fomat()
open file
str.replace
一.新款str.fomat()
1.>>> '12'.zfill(5)
'00012'
2.>>> print('one {},one {}'.format('world','dream'))
one world,one dream
3.>>> print('one {1},one {0}'.format('world','dream'))
one dream,one world
4.>>> print('one {0},one {1}'.format('world','dream'))
one world,one dream
5.>>> print('one {a},one {b}'.format(a='world',b='dream'))
one world,one dream
二.open file
1.打开模式:
r(只读)默认
w(已经存在的同名文件将被删掉)
a(追加)
r+(可读可写)
b(二进制)
备注:(Unix上是 \n
, Windows上是 \r\n)
f=open('file.txt','r')
2.文件对象操作方法
f.read # 读取整个文件
f.readline #读一行
f.readlines #读所有,列表的方式,每行一个。
for line in f: #遍历文件
print(line,end='')
f.write('tom') #写入文件
f.tell #指针位置
3.推荐用法
>>>with open('tab.py','r') as f:
... read_data=f.read()
三.str.replace
>>>str = "this is string example....wow!!! this is really string";
>>>print str.replace("is", "was");
>>>print str.replace("is", "was",2);
四.
五.循环技巧
1.字典items
f={1:'apple',2:'banana',3:"mango"}
for k,v in f.items():
print(k,v)
2.enumerate
for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v) 3.zip
>>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print('What is your {0}? It is {1}.'.format(q, a)) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.