The core data types of Python learning

Source: Internet
Author: User
Tags set set string methods

Python Core data types

Object Type Example

Digital 1234,-345

String ' spam '

list [1,3, ' DS ']

Tuples (1, ' spam ', 6)

Dictionary {' name ': ' Lili ', ' Age ': 12}

File myfile =open (' Test.text ', ' W)

Set set (' ABC ')

Other Types None Boolean type

Programming unit type functions, modules, classes

Digital

  Add, subtract, multiply, divide, needless to say, +-*/

* * indicates that the exponentiation 2**3 represents 2 of the three-square result is 8

>>>2**100

1267650600228229401496703205376L

Will find that even a large number, Python can be output correctly, the result may be saved with a string,

In addition to expressions, there are some common math modules that are distributed with Python, which are just the extra toolkits we import for use
Import Math
>>>math.pi


Import Random
>>>random.random ();
string
In Python we can also reverse the index, starting with the last
s = "Dhsaj"
>>>S[-1]
J
>>>s[-2]
A
In addition to a simple positional index, the sequence supports a so-called Shard operation. This is a one-step way to implement the entire Shard
s = "spam"
>>>s[1:3]
Pa
>>>s[1:] All sequences starting with ordinal 1
Pam
>>>s
Spam
>>>s[0:3]
Spa
>>>s[:3] From the beginning to the sequence preceded by the ordinal 3
Spa
>>>S[:-1] The sequence from the beginning to the last
Spa
>>>s[:] From the beginning to the last sequence
Spam

Strings are also supported for merging by adding good
s = "spam" + "name"
>>>s
Spamname
>>>s*2 repeat two times
Spamnamespamname

Non-denaturing
Python strings cannot be changed after they are created
s = "spam"
>>>s[0] = ' Z '
Error
s = ' Z ' +s[1:];
>>>s
Zpam

Type-specific methods
Find can do a string lookup
Replace will search and replace the global
s = "spam"
>>>s.find ("Pa");
1
>>>s.replace ("Pa", "XYZ");
Sxyzpam
>>>s
Spam

Although the names of these string methods are changed by meaning, but here we do not change the original string, but instead will create a new string as the result, because the string has immutability

line = "AAA,BBB,CCC,DDD";
>>>line.split (', '); Splitting a string into a city a list of strings
[' AAA ', ' BBB ', ' CCC ', ' DDD ']
s = ' spam '
>>>s.upper () Change case
SPAM
>>>s.isalpha () test string contents
True
line = ' aaa,bbb,ccc\n ';
>>>line = Line.rstrip () Removes the space character from the right
>>>line
' AAA,BBB,CCC '

The string also supports a high-level substitution operation called formatting,
>>> '%s,eggs,and%s '% (' spam ', ' spam ')
' Spam,eggs,and,spam '

>>> ' {0},eggs,and{1} '. Format (' spam ', ' spam ')
' Spam,eggs,and,spam '

ask for help
The previous section of the method is representative, but only a few examples of strings, you can call the built-in Dir function, will return a list, including all the properties of the object,

>>>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__ ', ' __setat ' Tr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' _formatter_field_name_split ', ' _formatter_parser ', ' capitalize ' , ' center ', ' count ', ' decode ', ' encode ', ' endswith ', ' expandtabs ', ' find ', ' format ', ' Index ', ' isalnum ', ' isalpha ', ' ISD Igit ', ' islower ', ' isspace ', ' istitle ', ' isupper ', ' join ', ' ljust ', ' lower ', ' lstrip ', ' partition ', ' replace ', ' rfind ' , ' Rindex ', ' rjust ', ' rpartition ', ' rsplit ', ' Rstrip ', ' Split ', ' splitlines ', ' startswith ', ' strip ', ' swapcase ', ' title ', ' Translate ', ' upper ', ' Zfill ']

The Dir function simply gives the name of the method, to query what they do, can pass parameters to the Help function
>>>help (' SSS '. Replace)
Help 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.


List
Python lists are not like the C language that requires a uniform type, Python lists can hold different types
Because the list is mutable, most of the list's methods will change the list object in place, rather than creating a new list

L = [N, "Das", 34];
>>>len (L)
3
>>>L[0]
12
>>>L[:-1]
"Das"
>>>l+[4,5,6]
["Das", 34,4,5,6]
>>>l.append (' AA ');
[' Das ', ' AA ']
>>>l.pop (2)
[A, ' Das ', AA]
>>>l.sort () sort
>>>l.reverse (); Flip
The list does not have a fixed size, but it still makes it impossible to access data beyond the end of the footer
------------------------------------------------------------
Nesting
Python can support arbitrary nested forms
Is that you can nest another list or even a single ancestor in one list.
---------------------------------------------------------------
List parsing

m=[[+],
[4,5,6],
[7,8,9]
];
>>>cols = [row[1] for row in M]; Remove the second column from M the row corresponds to each list element in M
>>>cols
[2,5,8]
>>> cols = [row[1] for row in m if row[1]%2 = = 0] Also support judgment statement
[2,8]
>>> double = [c*2 for C in "spam"];
>>>double
[' SS ', ' pp ', ' AA ', ' mm '];

Dictionary

A dictionary is not a sequence, but a mapping that is stored by a key rather than a relative position, but simply by mapping the key to a value

>>>d = {' food ': ' spam ', ' Color ': 4}
>>>d[' food ']
' Spam '
>>>d = {' name ': {' last ': Smith, ' first ': ' Bob '},
' Age ': 23,
' Job ': ' AA '}
>>>d[' name ']
{' Last ': Smith, ' first ': ' Bob '},
>>>d[' name ' [' first ']
' Bob '
>>>d = {' A ': 1, ' C ': 2, ' B ': 3}
>>> li = List (D.keys ())
>>>li
[' A ', ' C ', ' B ']
>>> Li.sort ();
>>> Li
[' A ', ' B ', ' C '];

Meta-group
is basically an immutable list.

>>> t = (1,2,3,4)
>>>len (t)
4
>>>t + (5,6);
(1,2,3,4,5,6)
In 3.0 by two proprietary methods
T.index (4)
3
T.count (3)
1
also supports mixed types and nesting, but not growth or shortening,

file
To create a file object, you need to call the built-in function, and an operation mode,

>>>f = open (' File1.txt ', ' W ')
>>>f.wirte (' hello\n ')
>>>f.write (' world\n ')
>>>f.close ();


>>>f = open (' File1.txt ', ' R ') R RB
>>>str = F.read ()
>>>f.close ()
>>>str
>>

----------------------------------
>>> L = [1,2,3,4]
>>> Type (l)
<type list>
>>> type (Type (l))
<type Type>
The following three types are used to determine the type of
if (type (l) = = Type ([])) {
}
if (type (l) = = list) {
}
if (Isinstance (l,list)) {
}
------------------------------ ----------------------------------------------
user-defined class

Class student:
     def  __init__ (self,name):
        self.name = name;
    def  GetName (self):
        return self.name;
     def setName (self,name):
        self.name = name;

STU1 = student (' Lil ');
name = Stu1.getname ();
Print (name);  

Stu1.setname (' aaa ');
Name = Stu1.getname ();
Print (name);


Python learning core data types

Related Article

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.