"Python CookBook2" chapter I text-control case && Access substring

Source: Internet
Author: User
Tags function prototype unpack

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

Standard
Format C Type Python Typesize 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.