您的位置:首页 > 编程语言 > Python开发

Python cookbook - 读书笔记

2013-06-28 09:26 267 查看
Before:

python built-in function: docs

我只想学function map(), THIS  - 摘: map(foo, seq) is equivalent to [ foo(x) for x in seq]

               - (看这个帖子,我好像明白了什么。好像第一次明白了,什么是“函数式编程”。)

1.9 - 简化字符串的 translate 方法的使用

WAIT- -!

1.10 - 过滤字符串中不属于制定集合的字符

  1. 利用string.translate()处理中文,必须使用unicode。ASCII不能处理中文。

    这个问题花了我一个上午,哈哈,THIS

#! /usr/bin/python
#Filename: translate.py

transTable = { ord('1'): u'一', ord('2'): u'二'}
unicodeStr = u'123'
print unicodeStr.translate(transTable)


1.13 - 访问子字符串

  1. Python struct


struct.unpack_from(fmt, buffer[, offset=0])

Unpack the buffer according to the given format. The result is a tuple even if it contains exactly one item. The buffer must contain at least the amount of data required by the format (len(buffer[offset:]) must be at least calcsize(fmt)).

struct.calcsize(fmt)

Return the size of the struct (and hence of the string) corresponding to the given format.



>>> import struct
>>> baseformat = '5s 3x 8s 8s'
>>> theline = '123456789012345678901234567890'
>>> numremain = len(theline) - struct.calcsize(baseformat)
>>> format = '%s %ds' % (baseformat, numremain)
>>> format
'5s 3x 8s 8s 6s'
>>> l, s1, s2, t = struct.unpack(format, theline)
>>> print l, s1, s2, t
12345 90123456 78901234 567890


1.18 - 一次完成多个替换

关键是 import re。 Python的 正则表达式re 怎么用? THIS

END
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: