A brief introduction to several data types in Python

Source: Internet
Author: User
Tags sublime text
In general, the data types in Python are grouped into the following categories:

Number (numeric)         includes Int,long,float,complex  string (string)        such as: Hello, "Hello", and hello  list (list)          for example: [[+] , [1,2,3,[1,2,3],4]  Dictionary (dictionary)       for example: {1: "Nihao", 2: "Hello"}  Tuple (tuple)          for example: (1,2,3,ABC) Bool (Boolean)          include true, False  

Because Python considers everything to be an object, Python does not have to declare the type of a variable as much as some other high-level language.

For example, I'm assigning a variable i to a 100,python implementation:

The implementation of C #:

The following one by one briefly describes these data types

Number Type

int and long

The reason for putting int and long together is that the int and long are not distinguished after python3.x, and are unified with int. The python2.x is still differentiated. Here I take Python2.7 as an example:

>>> i = ten >>> type (i) 
 
  
   
    >>> i=10000000000 >>> type (i) 
  
    
  
   
 
  

So why 10 is int,10000000000 is a long, of course, this is related to the maximum value of int, the maximum value of int type is 231-1, that is 2147483647, can also be used sys.maxint.

Why use the above method to find the value is long type (after the number plus ' L ' means long type), because the value of 2**31 is 2147483648, this value is a long type, with a long type minus 1, the result is a long, But actually the maximum value of int is 2147483647.

>>> type (2147483647) 
 
  
   
   >>> type (2147483648) 
  
    
  
   
 
  

Float type

Float type and other languages float basically consistent, floating-point number, white, that is, with decimal points, precision and machine-related. For example:

>>> i = 10000.1212 >>> type (i) 
 
   
 
  

Complex: plural type, specific meaning and usage you can view the relevant documents yourself.

String type

There are three ways to declare a string: single quotes, double quotes, and three quotation marks (including three single or three double quotation marks). For example:

There are two data types for strings in Python: The str type and the Unicode type. The STR type uses ASCII encoding, which means that it cannot represent Chinese. Unicode types are Unicode encoded and can represent any character, including Chinese and other languages. And there is no char type in python like the C language, even a single character is a string type. Strings are ASCII-encoded by default, and you need to precede the string with ' u ' or ' u ' if you want to display the declaration as a Unicode type. For example:

Because of the frequent manipulation of strings in the project, and because of the many problems that occur with string encoding problems, here is a question about the encoding of strings. In the process of dealing with Python, you often encounter ASCII, Unicode, and UTF-8 three encodings. Please refer to this article for a specific introduction. I simply understand that ASCII encoding is suitable for English characters, Unicode is suitable for non-English characters (such as Chinese, Korean, etc.), while Utf-8 is a stored and transmitted format that encodes the Uncode character (encoded in 8-bit units). For example:

Explanation: Declares the Unicode string "Han", whose Unicode encoding is "\u6c49", after Utf-8 encoding conversion, its encoding becomes "\xe6\xb1\x89".

A summary of the experience for coding:

1. Declare the encoding format in the Python file header;

#-*-Coding:utf-8-*-
2. Uniformly declare a string as a Unicode type, that is, by adding u or U before the string;

3. For the operation of file read and write, it is recommended to apply Codecs.open () instead of the built-in open (), follow a principle, in which format to write, in which format to read;

Suppose that there are "Chinese kanji" characters in a text file saved in ANSI format, and if you use the following code directly, and you want to print it out on the GUI or in an IDE (for example, in sublime text or in Pydev), garbled or abnormal characters will appear. Because codecs reads the content according to the encoding format of the text itself:

Use the following method (only works with Chinese):

#-*-Coding:utf-8-*-  import codecs  f = Codecs.open ("d:/test.txt") content = F.read () f.close ()  if Isinstanc E (content,unicode): Print   content.encode (' utf-8 ')   print "Utf-8" Else:   print content.decode (' GBK '). Encode (' Utf-8 ')  

List type

A list is a modifiable collection type whose elements can be basic types such as numbers, strings, or collection objects such as lists, tuples, dictionaries, or even custom types. It is defined in the following way:

>>> nums = [1,2,3,4] >>> type (nums) 
 
  
   
   >>> print nums [1, 2, 3, 4] >>> STRs = ["Hello", "World"] >>> print STRs [' Hello ', ' world '] >>> lst = [1, "Hello", False,nums,strs] >>> ; Type (LST) 
  
   
    
    >>> Print LST [1, ' Hello ', False, [1, 2, 3, 4], [' Hello ', ' World ' 
  
   
 
   ]

Indexed access to list elements, index starting at 0, support negative index, 1 is the last.

Support for Shard operations, access to elements within a range, support for different steps, data insertion and replication using shards

Nums = [1,2,3,4,5] Print Nums[0:3] #[1, 2, 3] #前三个元素  print nums[3:]  #[4, 5]  #后两个元素  print nums[-3:] #[3, 4, 5] #后三个元素 not supported nums[-3:0]  Numsclone = nums[:]   print Numsclone  #[1, 2, 3, 4, 5] copy operation  Print Nums[0:4:2]  # [1, 3]  Step 2  Nums[3:3] = ["Three", "four"]  #[1, 2, 3, ' Three ', ' four ', 4, 5] between 3 and 4 insert  nums[3:5] = []  

supports addition and multiplication operations

Lst1 = ["Hello", "world"] lst2 = [' good ', ' time '] print lst1+lst2 #[' hello ', ' world ', ' good ', ' time ']  

List of supported methods, you can view the public methods supported by the list in the following ways:

>>> [x for X in Dir ([]) If not X.startswith ("__")] [' Append ', ' count ', ' extend ', ' index ', ' Insert ', ' Pop ', ' Remov  E ', ' reverse ', ' sort '] def compare (x, y): return 1 if x>y else-1 # "append" Insert element at the end of the list LST = [1,2,3,4,5] Lst.append (6) Print LST #[1, 2, 3, 4, 5, 6] lst.append ("Hello") print lst #[1, 2, 3, 4, 5, 6] # "Pop" deletes an element and returns the value of this element supports indexing defaults to the last  x = Lst.pop () print X,lst #hello [1, 2, 3, 4, 5, 6] #默认删除最后一个元素 x = lst.pop (0) print X,lst #1 [2, 3, 4, 5, 6] Delete the first element # "Count" returns the number of occurrences of an element print Lst.count (2) #1 # "Extend" extension list This method differs from the "+" operation in that the method changes the original list, and the "+" operation produces a new list lstextend = ["Hello" , "World"] lst.extend (lstextend) print LST #[2, 3, 4, 5, 6, ' hello ', ' the ' "on the basis of LST extended lstextend come in #" index "returns a value An index position that appears once, if not found, throws an exception to print lst.index ("Hello") #5 #print lst.index ("Kitty") #ValueError: ' Kitty ' is a not in List exception # "R Emove "Removes an element from the list, if the item to be removed does not exist, throws an exception with no return value lst.remove (" Hello ") print lst #[2, 3, 4, 5, 6, ' World ']" Hello "removed #lst. Remove ("Kitty") #ValueErroR:list.remove (x): X not in List # "reverse" means reverse right is the list element in reverse order, no return value print LST #[2, 3, 4, 5, 6, ' World ' lst.reverse () Print LST #[2, 3, 4, 5, 6, ' World '] # "sort" Sort print lst #由于上面的反转 currently sorted for [' World ', 6, 5, 4, 3, 2] Lst.sort () print L St #排序后 [2, 3, 4, 5, 6, ' world '] nums = [10,5,4,2,3] print nums #[10,5,4,2,3] Nums.sort (Compare) print Nums #[2, 3,  4, 5, 10]

The list is converted to an iterator.

A so-called iterator is an object that has the next method, which does not require any arguments at the time of the call. When the next method is called, the iterator returns its next value. If the next method is called, but the iterator has no value to return, a Stopiteration exception is thrown. The advantage of iterators relative to lists is that using iterators does not have to add the list to memory at once, but you can access the data of the list in turn.

Still use the method above to view the public method of the iterator:

Yes, there is only next one method, for an iterator, you can do this:

LST = [1,2,3,4,5] lstiter = iter (LST) for  I in range (len (LST)):   print Lstiter.next () #依次打印   1   2   3   4   

Tuple type

Tuple types, like lists, are also sequences, unlike lists, where tuples are not modifiable. The declaration of the tuple is as follows:

LST = (0,1,2,2,2) lst1= ("Hello",) Lst2 = ("Hello") print type (lst1)  #
 
  
   
   There is only one element followed by a comma or str type Print type (lst2)  #
  
    
  
   
 
  

Dictionary type

A dictionary type is a collection of key-value pairs, similar to JSON objects in dictionary or JS in C # . The method of initialization is as follows:

Dict1 = {} print type (Dict1)   #
 
  
   
   declares an empty dictionary  dict2 = {"Name": "Kitty", "Age":  #直接声明字典类型  DICT3 = Dict ([("Name", "Kitty"), ("Age",)]) #利用dict函数将列表转换成字典  dict4 = dict (name= ' Kitty ', age=18)      # Use the Dict function to convert the keyword argument to dictionary  dict5 = {}.fromkeys (["Name", "Age"])   #利用fromkeys函数将key值列表生成字典, the corresponding value is none  {' Age ': None, ' Name ': none} 
 
  

Dictionary basic Methods of operation:

# "add Element"  Dict1 = {} dict1["MyKey"] = "Hello World"   #直接给一个不存在的键值对赋值 Add new element immediately  dict1[(' My ', ' key ') = "This key is a tuple "  #字典的键可以是任何一中不可变类型, such as number, string, tuple, etc.  #" key-value pairs "Print len (dict1)  #" Check if it contains a key "print" MyKey "in dict1< c21/> #True Check if a key value of MyKey is included in the print "Hello" in Dict1     #False  # "delete" del dict1["MyKey"]      

Continue to use the method above to view all the public methods of the dictionary:

>>> [x for x in Dir ({}) if not X.startswith ("__")] [' Clear ', ' copy ', ' Fromkeys ', ' get ', ' has_key ', ' Items ', ' iter Items ', ' iterkeys ', ' itervalues ',  


Dict.clear () Delete all the elements in the dictionary

Dict.copy () Returns a copy of the dictionary (shallow copy)

Dict.get (Key,default=none) Returns the value of the key in the dictionary dict, or the value of the default if the key is not present in the dictionary (note that the default value of the parameter is None)

Dict.has_key (Key) returns True if the key (key) exists in the dictionary, otherwise false is returned. After the Python2.2 version introduced in and not, this method is almost obsolete, but still provides a working interface.

Dict.items () Returns a list containing the tuple (key, value) in the dictionary

Dict.keys () Returns a list containing the keys in the dictionary

Dict.values () Returns a list that contains all the values in the dictionary

The Dict.iter () method Iteritems (), Iterkeys (), and itervalues () are different from the non-iterative methods they correspond to, but they return an iterator instead of a list.

Dict.pop (key[, default]) is similar to method get () If the key key exists in the dictionary, deletes and returns Dict[key], and throws a Keyerror exception if the key key does not exist and the value of default is not given.

Dict.setdefault (Key,default=none) is similar to method set (), and is assigned a value by Dict[key]=default if the key key is not present in the dictionary.

Dict.setdefault (Key,default=none) is similar to method set (), and is assigned a value by Dict[key]=default if the key key is not present in the dictionary.
Boolean type

Boolean types, which are true and false, are basically consistent with Boolean types in other languages. The typical Boolean values are listed below

print bool (0)  #False print bool (1)  #True print bool ( -1) #True  
  • 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.