Control Case
Task:
Turns a string from uppercase to lowercase, or to a row.
Solution:
>>> 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
Accessing substrings
Task:
Gets a portion of a string.
Solution:
Slicing is a good way, but it can only get one field at a time:
Afield = Theline[3:6]
If you also need to consider the length of the field, Struct.unpack may be more appropriate. For example:
>>>Importstruct>>> 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'
Note:
Struct.calcsize is used to calculate the length of the result of a format string, such as: Struct.calcsize (' II '), which returns 8
Format |
C Type |
Python Type | Standard
size |
Notes |
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 is used to convert the value of Python to a string based on a format character (because there is no byte type in Python, you can interpret the string here as a stream of bytes, or a byte array)
Struct.unpack does work just as opposed to struct.pack, which is used to convert byte streams into Python data types. The function prototype is: Struct.unpack (FMT, String), which returns a tuple.
"Python CookBook2" chapter I text-control case && Access substring