《python cookbook》chapter 1
2019獨角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
chapter1 文本
1.9 簡化字符串的translate方法的使用
translate方法在str和string模塊中都有:?str.translate(table[, deletechars])和string.translate(s, table[, deletechars])。deletechars為需要刪除的字符集合,table為替換表,可以用string.maketrans(from, to)生成,字符串from和to對應(yīng)長度相等。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') #第一個參數(shù)為操作字符串 >>> dst 'abcdefghi' >>> src 'Abc1Def2Ghi3' >>>
1.13 訪問子字符串
關(guān)于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'. #表示重復(fù)的次數(shù)
? ? 1.1)For the 's'?(對應(yīng)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. 格式中的空白會被忽視,數(shù)字與重復(fù)格式符號之間不能有空白。
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字節(jié)序。 >>> 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的功能看作與結(jié)構(gòu)體一樣
關(guān)于三元運算符
lasfield and s or x 等同于C語言中的三元運算符 lastfield ? s : x
轉(zhuǎn)載于:https://my.oschina.net/acemumu/blog/268942
總結(jié)
以上是生活随笔為你收集整理的《python cookbook》chapter 1的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Aop 切点表达式
- 下一篇: 第6章系统数据文件和信息总结