《python cookbook》chapter 1

chapter1 文本

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

translate方法在str和string模块中都有: str.translate(table[, deletechars])和string.translate(s, table[, deletechars])。deletechars为需要删除的字符集合,table为替换表,可以用string.maketrans(from, to)生成,字符串from和to对应长度相等。translate返回的是源字符串的副本(操作后),也就是不会改变源字符串s。

>>> import string
>>> src = 'Abc1Def2Ghi3'
>>> table = string.maketrans('ADG', 'adg')  #将A->a, D->d, G->g. ->改为
>>> dst = src.translate(table, '123')  #删除1, 2, 3
>>> dst
'abcdefghi'
>>> src    #src不变,dst为副本操作
'Abc1Def2Ghi3'
>>> dst = string.translate(src, table, '123') #第一个参数为操作字符串
>>> dst
'abcdefghi'
>>> src
'Abc1Def2Ghi3'
>>>



1.13 访问子字符串

关于struct模块


1) A format character may be preceded by an integral repeat count. For example, the format string'4h'means exactly the same as'hhhh'. #表示重复的次数

    1.1)For the 's' (对应char[])format character, the count is interpreted as the size of the string, not a repeat count like for the other format characters; for example,'10s'means a single 10-byte string, while'10c'means 10 characters. 

2) Whitespace characters between formats are ignored; a count and its format must not contain whitespace though. 格式中的空白会被忽视,数字与重复格式符号之间不能有空白。

3)  The 'P' format character is only available for the native byte ordering (selected as the default or with the'@'byte order character). 'P'表示void*类型,只支持'@' native字节序。
>>> record = 'raymond   \x32\x12\x08\x01\x08'
>>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)

>>> from collections import namedtuple
>>> Student = namedtuple('Student', 'name serialnum school gradelevel')
>>> Student._make(unpack('<10sHHb', record))
Student(name='raymond   ', serialnum=4658, school=264, gradelevel=8)

注:可将namedtuple的功能看作与结构体一样


关于三元运算符

lasfield and s or x 等同于C语言中的三元运算符 lastfield ? s : x


你可能感兴趣的:(《python cookbook》chapter 1)