1. 字符串前加 r 表示不处理转义字符,即不转义。
print(r'\taa') ------'\taa'
2. 字符串前加r表示unicode编码
3. 字典排序
1 下面的是按照value的值从大到小的顺序来排序。
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)
print dict
输出的结果:
[('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]
下面我们分解下代码
print dic.iteritems() 得到[(键,值)]的列表。
然后用sorted方法,通过key这个参数,指定排序是按照value,也就是第一个元素d[1的值来排序。reverse = True表示是需要翻转的,默认是从小到大,翻转的话,那就是从大到小。
2 对字典按键(key)排序:
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[0]) d[0]表示字典的键
print dict
4. 字符串转数字
<span style="font-size:14px;">>>> import string
>>> string.atoi('34')
34
>>> int('34')
34
>>> string.atof('34')
34.0
>>> float('34')
34.0</span>
5. 读取文件每行内容存至list
stopw = [line.strip().decode('utf-8') for line in open('D:\\Python27\\stopword.txt').readlines()]
6. str.format
自2.6开始,增加了str.format.
In [1]: '{0},{1}'.format('kzc',18)
Out[1]: 'kzc,18'
In [2]: '{},{}'.format('kzc',18)
Out[2]: 'kzc,18'
In [3]: '{1},{0},{1}'.format('kzc',18)
Out[3]: '18,kzc,18'
字符串的format函数可以接受不限个参数,位置可以不按顺序,可以不用或者用多次,不过2.6不能为空{},2.7才可以。
通过关键字参数
In [5]: '{name},{age}'.format(age=18,name='kzc')
Out[5]: 'kzc,18'
7. 计算执行时间
方法1
import datetime
starttime = datetime.datetime.now()
#long running
endtime = datetime.datetime.now()
print (endtime - stratime) #timedelta类型
print (endgame - stratum).total_seconds #float
方法 2
start = time.time()
run_fun()
end = time.time()
print end-start
函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式
>>> aa = '哈哈'
>>> print aa
哈哈
>>> print repr(aa)
'\xe5\x93\x88\xe5\x93\x88'
l = ["你好", "猎鹰"]
ll = u"你好"
print (ll.encode('utf-8') in l) # True
print (ll in l) #False ,<span style="color: rgb(102, 102, 102); font-family: 宋体, Arial;font-size:10px;">UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal</span>
10. 将序列转成字符串(join)及字符串分割
join:在序列中添加元素
split: 将字符串分解成序列
两者为互逆方法
Python代码
s = "as, asdas \r\nasda"
print s.split();
# result: ['as,', 'asdas', 'asda']
print "".join(s.split()); #<span style="color:#ff0000;">先split后jion就将\r\n删除了</span>
# result: as,asdasasda
l = "".join(s.split()).split(',');
print l;
# result: ['as', 'asdasasda']
建议先将字符串解码成unicode,split后再编码回去,可以消除分割字符在不同编码中的差异
11. strip 移除字符串头、尾的特定字符
str.strip([chars]);
默认删除\r\n\t及' '
12. 脚本所在路径及运行路径
os.path.split(os.path.realpath(__file__))[0] #脚本所在目录
而sys.path[0]是脚本运行路径
</pre></div><div>13。 json.dumps 输出中文</div><div><pre name="code" class="python">要输出中文需要指定ensure_ascii参数为False,如下代码片段:
json.dumps({'text':"中文"},ensure_ascii=False)
14. 可变与不可变对象
可变类型:list, dict
不可变类型:int, float, tuple, string
15.
>>> a = [1, 2, 3, 4]
>>> for e in a:
... if e == 2:
... a.remove(e)
... print e
...
1
2
4
>>> print a
[1, 3, 4]
>>>
可见,for e in a 应该是等同于for i in range(0, len(a)) 是同样的实现
16 enumerate
enumerate 函数用于遍历序列中的元素以及它们的下标:
>>> for i,j in enumerate(('a','b','c')):
print i,j
0 a
1 b
2 c
>>> for i,j in enumerate([1,2,3]):
print i,j
0 1
1 2
2 3
>>> for i,j in enumerate({'a':1,'b':2}):
print i,j
0 a
1 b
>>> for i,j in enumerate('abc'):
print i,j
0 a
1 b
2 c
17. os.getcwd() 与os.path.realpath(__file__)
前者获取脚本运行目录。注意,不是脚本所在的目录
后者获取脚本的文件路径。返回的字符串包含文件名。 os.path.split( os.paht.realpath(__file__) )[0]是文件所在目录