Python Learning manual--1 Introduction to Python object types

Source: Internet
Author: User
Tags stack trace string methods



In Python, data appears as objects-whether it's built-in objects provided by Python, or objects created using Python or an extended language tool like the C extension library. Although this concept can be determined later, the object is nothing more than an intrinsic part, containing a collection of values and related operations,



Since the object is the most basic concept of Python, from this chapter we will thoroughly experience Python's built-in object types.






The Python program can be decomposed into modules, statements, expressions, and objects as follows:



1. The program is composed of modules



2. Module contains statements



3. Statement contains an expression



4. Expression creation and processing of an object






Why use built-in types



1. Built-in objects make programs easier to write.



2. Built-in objects are extended components.



3. Built-in objects tend to be more efficient than custom data structures.



4. Built-in objects are part of the language standard.



Python's core data types






Object Type example constants/Create



Digital 1234,3.1415,3+4j,decimal



String ' spam ', ' Guido ', ' B ' a\xolc '



List [1,[2, ' three '],4]



Dictionary {' food ': ' spam ', ' taste ': ' Yum '}



Tuples (1, ' spam ', 4, ' U ')



File myfile=open (' eggs ', ' r ')



Set set (' abc '), {' A ', ' B ', ' C '}



Other type types, NONE, Boolean



Programming unit type functions, modules, classes



Code stack trace for implementation -related type compilation






Digital:



The basic numeric type of Python is still fairly basic. Python's numbers support general mathematical operations. For example, the plus sign (+) represents addition, the asterisk (*) represents multiplication, and the double star (* *) represents the exponentiation.





>>> 123+222345>>> 2.65*410.6>>> 2**1001267650600228229401496703205376l

In addition to expressions, there are some common math modules that are distributed with Python, and the modules are just some of the additional toolkits we import for use.







>>> Import math>>> math.pi3.141592653589793>>> math.sqrt (85) 9.219544457292887

The Math module includes more advanced mathematical tools, such as functions, and the random module can be used as the generator and random selector for the number.







>>> import random>>> random.random () 0.30460311868409107>>> random.choice ([1,2,3,4]) 3 >>> Random.choice ([1,2,4,5]) 5

string:





Operation of the sequence



As a sequence, the string supports operations that assume that each element contains a positional order. For example, if we have a four-character string, we validate its length with the built-in Len function and get its individual elements through an index operation. (Python is case-sensitive)





>>> s= ' spam ' >>> len (S) Traceback (most recent call last):  File "<pyshell#14>", line 1, in < Module>    Len (s) nameerror:name ' s ' is not defined>>> Len (s) 4>>> s[0] ' s ' >>> s[1] ' p '

In Python, the index is encoded according to the first offset, that is, starting with 0, the index is 0, the second index is 1, and so on.





Notice how we're assigning a string to a variable named S here. However, Python variables do not need to be declared in advance. When a variable is assigned a value, it is created, it may be assigned to any type of object, and when the variable appears in an expression, it is replaced with its value.






In Pythonk, we were able to reverse the index, starting with the last





>>> s[-1] ' m ' >>> s[-2] ' a ' >>> S[len (S)-2] ' a '

It's worth noting that we can use arbitrary expressions in square brackets, not just numeric constants--as long as Python needs a value, we can use a constant, a variable, or any expression. Python's syntax is completely generic in this respect.








In addition to simply indexing from a location, the sequence also supports a so-called Shard operation, which is a way to extract the entire shard in one step. For example:





>>> S ' spam ' >>> s[1:3] ' pa '

Their general form is x[i:j], which means "take out the offset from I in X, but not include the content of the offset J".








In one Shard, the left boundary defaults to 0, and the right boundary defaults to the length of the Shard sequence. This introduces some variants of the common law.





>>> s[1:] ' pam ' >>> S[0:3] ' spa ' >>> S[:3] ' spa ' >>> s[:] ' spam '

Finally, as a sequence, the string also supports merging with the plus sign:







</pre><pre name= "code" class= "python" >>>> S ' spam ' >>> s+ ' XYZ ' spamxyz ' >>> s* 8 ' Spamspamspamspamspamspamspamspam '

Note the plus sign: for numbers, for addition, for strings for merging.








Non-denaturing



Note: In this previous example, the original string could not be changed by any action. Each string is defined as the result of generating a new string, because the python in the string is immutable-it cannot be changed in place after it is created.





>>> S ' spam ' >>> s[0]= ' Z ' Traceback (most recent call last):  File "<pyshell#36>", line 1, in < ;module>    s[0]= ' z ' TypeError: ' str ' object does not support item assignment>>> s= ' Z ' +s[1:]>>> S ' Zpam '







type-specific methods:


Other sequences in Python also work, including lists and tuples. Despite this, in addition to the general sequence operation, there are some unique operations for the method existence (object function)



For example, the Find method of a string is the operation of a basic substring lookup (it returns an offset of an incoming substring, or 1 if it is not found), and the Replace method of the string will search for and replace the global.





>>> s.find (' Pa ') 1>>> s ' zpam ' >>> s.replace (' pa ', ' xyz ') ' Zxyzm ' >>> S ' zpam '

Although the naming of these string methods has a change in meaning, we do not change the original string here, but instead create a new string as the result-because the string is immutable, we must do so. The string method will be the number one tool for Pythonk Chinese text processing. Other methods can also be implemented by splitting the string into substrings, casing transforms, testing the contents of the string, and removing the space character after the string.



>>> S.isalpha () true>>> line= ' aaa,bbb,ccc,dd\n ' >>> line=line.rstrip () >>> Line ' AAA,BBB,CCC,DD '







The string also supports a high-level substitution operation called formatting, which can be used in the form of an expression (the original) and a string method invocation.




>>> '%s,eggs,and%s '% (' spam ', ' spam! ') ' spam,eggs,andspam! ' >>> ' {0},eggs,and{1} '. Format (' spam ', ' spam! ') ' spam,eggs,andspam! '

Ask for help:










>>> dir (s) [' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ', ' __getitem__ ', ' __getnewargs__ ', ' __getslice__ ', ' __gt__ ', ' __ Hash__ ', ' __init__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __mod__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ ' Ex__ ', ' __repr__ ', ' __rmod__ ', ' __rmul__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' _formatter_ ' Field_name_split ', ' _formatter_parser ', ' capitalize ', ' center ', ' count ', ' decode ', ' encode ', ' endswith ', ' expandtabs ', ' Find ', ' format ', ' Index ', ' isalnum ', ' isalpha ', ' isdigit ', ' islower ', ' isspace ', ' istitle ', ' isupper ', ' join ', ' ljust ', ' Lower ', ' lstrip ', ' partition ', ' replace ', ' rfind ', ' rindex ', ' rjust ', ' rpartition ', ' rsplit ', ' Rstrip ', ' Split ', ' Splitli ' Nes ', ' startswith ', ' strip ', ' swapcase ', ' title ', ' Translate ', ' upper ', ' Zfill '] 

The Dir function simply gives the name of the method. To query what they do, you can pass it to the help function.







>>> Help (S.replace)-On built-in function replace:replace (...)    S.replace (old, new[, Count])-string        Return a copy of string S with all occurrences of substring old    replaced by new.  If the optional argument count    is given, only the first count occurrences is replaced.





















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.