Python basics-built-in data types

Source: Internet
Author: User

Python basics-built-in data types
I. Introduction if you have used C or C ++, you should know that many of your work focuses on implementing data structures. You need to manage memory allocation and deploy the memory structure. These things are boring and often make you unable to concentrate on what you really want to achieve. In Python, many such boring jobs are removed. Python provides powerful object types as part of the Python language. To solve the problem, you do not need to write code to implement these structures. In addition, you do not need to implement your own data types. Because the built-in object type has many advantages. If you are a programmer, you must first know how to use it for beginners. Python built-in data type: You can use dir () to view the attributes and methods supported by data types: Numbers Strings Lists Dictionaries Tuples Files Other types Sets, type, None, boolean 2. number Type Literal Interpretion supported by Numbers | 1234,-24, 0 Normal intergers (C lons) 99999999999999l Long intergers (unlimited size) 1.23, 3.14e-10, 4E210 Floating-point numbers (C doubles) 0177, 0x9ff, 0xff Octal and hex literals for intergers3 + 4j, 3.0 + 4.0j, 3J Comples number literalsPython express Ion operators and precedureOperators Description | yield x Generator function send protocollambda args: expression Anonymous function generationx if y else z Ternary (Ternary) selection expressionx or y Logical OR (X is false to compare Y) x and y Logical AND (X is true to compare Y) not x Logical negation <, <=,>, >=, = ,! =, X is y, x is not y, x not in yx | y by bit or x ^ y by bit or x & y by bit and x <y, x> y shifts left by bit, right by-x + y, x-y plus, minus x * y, x % y, x/y, x/y multiply by-x, + x ,~ X, x ** y

# Some operations In [1]: 01,010,010 0Out [1]: (1, 8, 64) In [2]: 0x01,0x10, 0 xffOut [2]: (1, 16,255) In [3]: oct (64), hex (64), hex (255) Out [3]: ('000000', '0x40 ', '0xff') In [4]: int ('000000'), int ('000000', 8), int ('0x40', 16) Out [4]: (100, 64, 64)

 

In terms of number, the math module has many processing functions. Iii. Strings1 and String are also called seqeunce. strings are easy to use in Python, but the most complicated part is that there are many ways to write a String Single: quotes: 'spa "M' Double quotes:" spa'm "Triple quotes :"""... pam... "",'''... spam... ''' Escape sequence: "S \ tp \ na \ Om" Raw strings: r "C: \ new \ test. spm "Unicode strings: u" eggs \ u0020spam "2. Escape Character Escape Sequence Meaning \ newlineIgnored \ Backslash (\) \ 'single quote (') \" Double quote (") \ aASCII Bell (BEL) \ bASCII Backspace (BS) \ fASCII Formfeed (FF) \ nASCII Linefeed (LF) \ rASCII Carriage Return (CR) \ tASCII Horizontal Tab (TAB) \ vASCII Vertical Tab (VT) \ oooASCII character with octal value ooo \ xhh... ASCII character with hex value hh... 3. Basic operations
In [1]: a = 'abc' In [2]: 'abc' + 'def 'out [2]: 'abcdef 'In [3]: 'abc' * 3Out [3]: 'abcabcabc' In [5]: a [1] Out [5]: 'B' In [6]: a [] Out [6]: 'B' In [7]: a [] Out [7]: 'bc' In [8]: a [-1] Out [8]: 'C' In [9]: a [: 2] Out [9]: 'ac' 4. format the string In [10]: "% d % s % d you" % (1, 'spam', 4) Out [10]: '1 spam 4 you' Format SymbolConversion % ccharacter % sstring conversion via str () prior to formatting % isigned decimal integer % dsigned decimal integer % uunsigned decimal integer % ooctal integer % xhexadecimal integer (lowercase letters) % Xhexadecimal integer (UPPERcase letters) % eexponential notation (with lowercase 'E') % Eexponential notation (with UPPERcase 'E ') % ffloating point real number % gthe shorter of % f and % e % Gthe shorter of % f and % E

 

5. String Method
'Capitalize', # upper-case 'center', # S. center (width [, fillchar])-> string 'Count', # S. count (sub [, start [, end])-> int 'decode', # decode 'encode', # encode 'enabledwith', # end with 'pandtabs ', # S. expandtabs ([tabsize])-> string # The number of characters 'Find ', # S. find (sub [, start [, end])-> int 'format', # reference: http://blog.csdn.net/handsomekang/article/details/9183303 'index', # The same as find, however, if 'isalnum' is not found, # whether it is a number, which may contain 'isalpha', # whether it is an 'isdigit', and # whether it is a number 'islower ', # Whether it is lowercase 'isspace', # whether it is a space character 'istitle', # whether it is a title style, that is, the first letter of each word is capitalized 'isupper ', # whether it is capitalized 'join ', # In [33]: a = "yunzhonghe"; B = ""; B. join (a); Out: 'y u n z h o n g h e ''ljust', # S. ljust (width [, fillchar])-> Add a space 'lower 'to the right of string, # convert string to lower case 'lstrip', # Remove the left space 'partition', # S. partition (sep)-> (head, sep, tail), divided into three sections: 'replace ', # S. replace (old, new [, count])-> string 'rfind ', # find from the back. The function is the same as find 'rindex', # Same as above, if it cannot be found, an error occurs: 'partition ust ', # Add a space on the left 'rpartition', # Find 'rsplits' from the back, # S. rsplit ([sep [, maxsplit])-> list of strings 'rdstrip', # Restrict spaces on the Right To 'split ', # S. split ([sep [, maxsplit])-> list of strings use 'splitlines' as the separator, # Return the list of rows 'startswith ', # Who starts 'strip ', # Remove the space characters 'swapcase' on both sides, # Replace 'title' with uppercase letters, # convert to the title style 'translate', # S. translate (table [, deletechars])-> string 'uppper ', # convert to uppercase 'zfill' # Fill In 0 characters In [58]:. zfill (10); Out [58]: '0000000abc'

 

4. ListsLists: ordered object collection, access through offset, variable length, free nesting, and sequence change. 1. Basic operations
In [1]: l = ["abc",'def','ghi']  In [2]: l*3Out[2]: ['abc', 'def', 'ghi', 'abc', 'def', 'ghi', 'abc', 'def', 'ghi']  In [3]: [l] * 3Out[3]: [['abc', 'def', 'ghi'], ['abc', 'def', 'ghi'], ['abc', 'def', 'ghi']]  In [4]: l + ["xyz"]Out[4]: ['abc', 'def', 'ghi', 'xyz']  In [5]: l[1]Out[5]: 'def'  In [6]: l[1][1]Out[6]: 'e'  In [7]: l[0:2]Out[7]: ['abc', 'def']  In [8]: l1 = [x**2 for x in range(5)]  In [9]: l1Out[9]: [0, 1, 4, 9, 16]

 

2. List Method
'Append', # Add an element 'Count', # calculate the number of occurrences of an element 'extend', # Add a large number of elements 'index', # L. index (value, [start, [stop])-> integer -- return first index of value. 'insert', # L. insert (index, object) -- insert object before index 'pop', # retrieve a data 'delete', # delete a data 'reverse', # Flip 'sort 'sequentially # sort order

 

5. DictionariesDictionaries is also a flexible built-in data type. The list can be seen as an ordered object collector, while the Dictionary is an unordered collection. The item is retrieved by the key instead of the Offset.
In [19]: dir (dict) Out [19]: '_ class _', '_ cmp _', '_ contains __', '_ delattr _', # Delete attr '_ delitem _', # delete item '_ doc __', # comment out the document information '_ eq _', # equals '_ format _', '_ ge _', '_ getattribute __', '_ getitem _', '_ gt _', # greater than '_ hash _', '_ init __', '_ iter _', '_ le _', # less than or equal to '_ len _', # number of keys '_ lt __', # less than '_ ne _', # not equal to '_ new _', # '_ reduce _', '_ performance_ex __', '_ repr _', '_ setattr _', '_ setitem _', '_ sizeof _', '_ str __', '_ subclasshook _', 'clear', # clear the dictionary 'copy', # D. copy ()-> a shallow copy of D 'fromkeys ', # In [11]: dict. fromkeys ("yun", "test") Out [11]: {'N': 'test', 'U': 'test', 'y ': 'test'} 'get', # D. get (k [, d])-> D [k] if k in D, else d. d defaults to None. 'Has _ key', # D. has_key (k)-> True if D has a key k, else False 'items ', # D. items ()-> list of D's (key, value) pairs, as 2-tuples 'iteritems ', # D. iteritems ()-> an iterator over the (key, value) items of D 'iterkeys ', # 'itervalues', # 'keys', # D. keys ()-> list of D's keys 'pop', # D. pop (k [, d])-> v, remove specified key and return the corresponding value. 'popitem', # obtain some key-item data 'setdefault', # D. setdefault (k [, d])-> D. get (k, d), also set D [k] = d if k not in D 'update', # D. update ([E,] ** F)-> None. update D from dict/iterable E and F. if E present and has. keys () method, does: for k in E: D [k] = E [k] If E present and lacks. keys () method, does: for (k, v) in E: D [k] = v In either case, this is followed by: for k in F: D [k] = F [k] 'values', # D. values ()-> list of D's values 'viewitems ', # In [30]:. viewitems () # Out [30]: dict_items ([('age', 19), ('name', 'yzhonghe'), ('school ', 'hqu')]) 'viewkeys ', 'viewvalues'

 

6. TuplesTuple and List are similar. They are collected by type, but Tuple cannot be modified by bit. Tuple features: ordered collection of arbitrary objects, access by offset, immutable sequence, fixed length, and free nesting.
In [39]: dir (tuple) Out [39]: ['_ add _', # You can add '_ class _' to Tuple __', '_ ins INS _', '_ delattr _', '_ doc _', '_ eq _', '_ format __', '_ ge _', '_ getattribute _', '_ getitem _', '_ getnewargs _', '_ getslice __', '_ gt _', '_ hash _', '_ init _', '_ iter _', '_ le __', '_ len _', '_ lt _', '_ mul _', '_ ne _', '_ new __', '_ reduce _', '_ performance_ex _', '_ repr _', '_ rmul _', '_ setattr __', '_ sizeof _', # memory usage '_ str _', # You can call the str method '_ subclasshook _', 'Count ', # calculating the number of 'index' occurrences of a value] # viewing the index of a value

 

7. Files are named isolated buckets and managed by the operating system. Fp = open ("test.txt", w) open a file directly. If the file does not exist, create a file. 1. open Mode: w is opened in write mode, a is opened in append mode (starting from EOF and creating a file if necessary) r + w in read/write mode (see w) a + opens in read/write mode (see a) rb opens wb in binary read mode in binary write mode (see w) AB opens in binary append mode (see) rb + is opened in binary read/write mode (see r +) wb + is opened in binary read/write mode (see w +) AB + is opened in binary read/write mode (see a +) 2. File Method
Fp. read ([size]) # size is the read length, in bytes. readline ([size]) # Read a row. If the size is defined, it is possible that only part of the fp of the row is returned. readlines ([size]) # Use each row of the file as a member of a list and return this list. In fact, it is implemented by calling readline () cyclically. If the size parameter is provided, size indicates the total length of the read content, that is, it may be read only to a part of the file. Fp. write (str) # write str to the file. write () does not add a line break fp after str. writelines (seq) # Write All seq content to a file (multiple rows are written at one time ). This function is only faithfully written without adding anything to the end of each line. Fp. close () # close the file. Python will automatically close the file after a file is not used, but this function is not guaranteed, it is best to develop your own habit of closing. If a file is closed and operated on it, ValueErrorfp is generated. flush () # Write the buffer content to the hard disk fp. fileno () # returns a long integer "file tag" fp. isatty () # Whether the file is a terminal device file (in unix) fp. tell () # returns the current position marked by the file operation, starting with the file

 

Fp. next () # return the next line and move the operation mark of the file to the next line. Use a file... When a statement such as in file is called, the next () function is called to implement traversal. Fp. seek (offset [, whence]) # mark the file operation and move it to the offset position. This offset is generally calculated relative to the beginning of the file, and is generally a positive number. However, if the whence parameter is provided, it is not necessary. If the whence parameter is 0, it indicates that the calculation starts from the beginning, and 1 indicates that the calculation is based on the current position. 2 indicates that the origin is the end of the file. Note that if the file is opened in a or a + mode, the file operation mark is automatically returned to the end of the file during each write operation. Fp. truncate ([size]) # crop the file to the specified size. The default value is the location marked by the current file operation. If the size is larger than the file size, the file may not be changed depending on the system, or 0 may be used to fill the file with the corresponding size, it may also be added with random content. 8. postscript 1. There are almost so many basic types of Python for future reference.

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.