《Python CookBook2》 第一章 文本

控制大小写


任务:

  将一个字符串由大写转成小写,或者泛起到而行之。

解决方案:

>>> a = 'a'.upper()
>>> a
'A'
>>> b = 'b'.lower()
>>> b
'b'
>>> print "I loVe pythOn".capitalize()
I love python
>>> print "I loVe pythOn".title()
I Love Python

访问子字符串


任务:

  获取字符串的某个部分。 

解决方案:

  切片是个好方法,但是它一次只能取得一个字段:

afield = theline[3:6]

  如果还需要考虑字段的长度,struct.unpack可能更适合。例如:

>>> import struct
>>> baseformat = "5s 3x 8s 8s"
>>> theline = 'qqqwwweeerrrtttyyyaaasssdddfff'
>>> numremain = len(theline)- struct.calcsize(baseformat)
>>> format = "%s %ds" %(baseformat,numremain)
>>> len(theline)
30
>>> l,s1,s2,t = struct.unpack(format,theline)
>>> l
'qqqww'
>>> s1
'errrttty'
>>> s2
'yyaaasss'
>>> t
'dddfff'

注:

struct.calcsize用于计算格式字符串所对应的结果的长度,如:struct.calcsize('ii'),返回8

FormatC TypePython typeStandard sizeNotes
x pad byte no value    
c char string of length 1 1  
b signed char integer 1 (3)
B unsignedchar integer 1 (3)
? _Bool bool 1 (1)
h short integer 2 (3)
H unsignedshort integer 2 (3)
i int integer 4 (3)
I unsignedint integer 4 (3)
l long integer 4 (3)
L unsignedlong integer 4 (3)
q long long integer 8 (2), (3)
Q unsignedlong long integer 8 (2), (3)
f float float 4 (4)
d double float 8 (4)
s char[] string    
p char[] string    
P void * integer   (5), (3)

struct.pack用于将Python的值根据格式符,转换为字符串(因为Python中没有字节 (Byte)类型,可以把这里的字符串理解为字节流,或字节数组)

struct.unpack做的工作刚好与struct.pack相反,用于将字节流转换成python数据类型。它的函数原型为:struct.unpack(fmt, string),该函数返回一个元组。

原文地址:https://www.cnblogs.com/wuzhiming/p/3939338.html