Several data types in Python are briefly introduced.

Source: Internet
Author: User
Python has many built-in data types, such as integer, String, tuples, list, dictionary, and Boolean, the following describes in detail the data types in Python as follows:

Number (Number) includes int, long, float, complex String (String) for example: hello, "hello", hello List (List) for example: [1, 2, 3], [1, 2, 3, [, 3], 4] Dictionary (Dictionary) for example: {1: "nihao", 2: "hello"} Tuple (tuples) for example: (, 3, abc) Bool (Boolean) includes True and False

Because Python considers everything to be an object, Python does not need to manually declare the type of a variable as some other advanced languages do.

For example, I want to assign a value of 100 to a variable I. python implementation:

i=100 

C # implementation:

int i = 100; 

The following describes the data types

Numeric type

Int and long

The reason for putting int and long together is that after python3.x, int and long are not distinguished and int is used in a unified manner. Python2.x is differentiated. The following uses Python2.7 as an example:

>>> i = 10 >>> type(i) 
 
    >>> i=10000000000 >>> type(i) 
   
  
 

So why is 10 int and 10000000000 long? Of course, this is related to the maximum value of int. The maximum value of int type is 231-1, that is, 2147483647. You can also use sys. maxint.

>>> 2**31-1 2147483647L >>> sys.maxint 2147483647 

Why is the value obtained by using the above method long? ('L' is followed by a number to indicate a long value.) because the value of 2 ** 31 is 2147483648, this value is a long type. If we subtract 1 from a long type, the result is still a long type. However, the maximum value of the int type is 2147483647.

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

Float Type

The float type is basically the same as the float type in other languages. The floating point number, to put it bluntly, is the number of decimal points. The precision is related to the machine. For example:

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

Complex: the plural type. For more information about the meaning and usage, see related documents.

String type

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

>>> str1 = 'hello world' >>> str2 = "hello world" >>> str3 = '''hello world''' >>> str4 = """hello world""" >>> print str1 hello world >>> print str2 hello world >>> print str3 hello world >>> print str4 hello world 

There are two types of strings in Python: str and unicode. The str type adopts ASCII encoding, which means it cannot represent Chinese characters. The unicode type adopts unicode encoding and can represent any character, including Chinese and other languages. In addition, python does not have the char type in C language, even if a single character is also a string type. The default ASCII encoding of a string. to display the unicode type, add 'U' or 'U' to the front of the string '. For example:

>>> Str1 = "hello" >>> print str1 hello >>> str2 = u "China" >>> print str2 China

Because operations on strings often occur in projects and there are many problems with string encoding, let's take a look at the encoding of strings. When dealing with python, we often encounter three types of encoding: ASCII, Unicode, and UTF-8. For more information, see this article. I simply understand that ASCII encoding applies to English characters, Unicode applies to non-English characters (such as Chinese and Korean), and UTF-8 is a storage and transfer format, it is the reencoding of Uncode characters (in 8 bits ). For example:

U = u'han' print repr (u) # U' \ u6c49's = u. encode ('utf-8') print repr (s) # '\ xe6 \ xb1 \ x89' u2 = s. decode ('utf-8') print repr (u2) # U' \ u6c49'

Explanation: the unicode string "Han" is declared. Its unicode encoding is "\ u6c49". After UTF-8 encoding, its encoding is changed to "\ xe6 \ xb1 \ x89".

Summary of coding experience:

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

#-*-Coding: UTF-8 -*-
2. Declare the string as unicode type, that is, add u or U before the string;

3. For file read/write operations, codecs. open () is recommended to replace the built-in open (). Follow the principle that the format used for writing should be read in what format;

Assume that an ANSI text file contains Chinese characters. If you directly use the following code, in addition, garbled characters or exceptions may occur when printing in the GUI or in an IDE (for example, in sublime text or in pydev, because codecs reads content based on the encoding format of the text itself:

f = codecs.open("d:/test.txt") content = f.read() f.close() print content 

Use the following method instead (only for Chinese ):

# -*- coding: utf-8 -*-  import codecs  f = codecs.open("d:/test.txt") content = f.read() f.close()  if isinstance(content,unicode):   print content.encode('utf-8')   print "utf-8" else:   print content.decode('gbk').encode('utf-8')  

List type

A list is a set type that can be modified. Its elements can be numbers, strings, and other basic types, or list, tuples, dictionaries, and other collection objects, it can even be a custom type. The definition is as follows:

>>> 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']] 
  
 

Access list elements using indexes. The index starts from 0 and supports negative index.-1 is the last one.

>>> lst = [1,2,3,4,5] >>> print lst[0] 1 >>> print lst[-1] 5 >>> print lst[-2] 4 

Supports sharding and allows you to access elements in a certain range. You can use shards to insert and copy data.

Nums = [1, 2, 3, 4, 5] print nums [0: 3] # [1, 2, 3] # print nums [3:] # [4, 5] # the last two elements print nums [-3:] # [3, 4, 5] # The last three elements do not support nums [-3:0] numsclone = nums [:] print numsclone # [1, 2, 3, 4, 5] copy operation print nums [] # [1, 3] Step 2 nums [] = ["three ", "four"] # [1, 2, 3, 'three ', 'four', 4, 5] Insert nums [3: 5] = [] # [1, 2, 3, 4, 5] Replace 4th and 5th elements with [] to delete ["three", "four"]

Supports addition and multiplication

lst1 = ["hello","world"] lst2 = ['good','time'] print lst1+lst2 #['hello', 'world', 'good', 'time']  print lst1*5 #['hello', 'world', 'hello', 'world', 'hello', 'world', 'hello', 'world', 'hello', 'world'] 

You can view the public methods supported by the list as follows:

>>> [X for x in dir ([]) if not x. startswith ()] ['append', 'Count', 'extend', 'index', 'insert', 'pop', 'delete', 'reverse ', 'sort '] def compare (x, y): return 1 if x> y else-1 # [append] Insert the element lst = [1, 2, 4, 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 return the value of this element. The index is the last x = lst by default. pop () print x, lst # hello [1, 2, 3, 4, 5, 6] # Delete the last element x = lst by default. pop (0) print x, lst #1 [2, 3, 4, 5, 6] Delete the first element # [count] returns the number of times that an element appears print lst. count (2) #1 # [extend] extended list this method differs from the "+" operation in that this method changes the original list, the "+" Operation generates a new list lstextend = ["hello", "world"] lst. extend (lstextend) print lst # [2, 3, 4, 5, 6, 'Hello ', 'World'] extended lstextend on the basis of lst # [index] returns the index location where a value appears for the first time. If it is not found, an exception print lst will be thrown. index ("hello") #5 # print lst. index ("kitty") # ValueError: 'Kitty 'is not in list exception # [remove] remove an element from the list. If the item to be removed does not exist, will throw an exception and 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] indicates reverse. That is, the list elements are arranged in reverse order. No returned value is print lst # [2, 3, 4, 5, 6, 'World'] lst. reverse () print lst # [2, 3, 4, 5, 6, 'World'] # [sort] sorting print lst # As the previous reverse order is ['World', 6, 5, 4, 3, 2] lst. sort () print lst # [2, 3, 4, 5, 6, 'World'] nums = [, 5, 3] print nums, 3] nums. sort (compare) print nums # [2, 3, 4, 5, 10]

List to iterator.

The so-called iterator is an object with the next method (this method does not require any parameters when called. 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. Compared with the list, the iterator does not have to add the list to the memory at a time, but can access the list data in sequence.

You can still use the following method to view the public method of the iterator:

lst = [1,2,3,4,5] lstiter = iter(lst) print [x for x in dir(numiter) if not x.startswith()] >>>['next'] 

Yes, there is only one method for next. For an iterator, you can perform the following operations:

Lst = [1, 2, 3, 4, 5] lstiter = iter (lst) for I in range (len (lst): print lstiter. next () # print 1 2 3 4 5 in sequence

Tuples

The same type as the list, the tuples are also a sequence. Unlike the list, the tuples cannot be modified. The declaration of tuples is as follows:

Lst = (0, 1, 2, 2) lst1 = ("hello",) lst2 = ("hello") print type (lst1 )#
 
  
Only one element is followed by a comma; otherwise, the str type is print type (lst2 )#
   
  
 

Dictionary type

The Dictionary type is a set of key-value pairs, similar to the Dictionary in C #. Or json object in js. The initialization method is as follows:

Dict1 = {} print type (dict1 )#
 
  
Declare an empty dictionary dict2 = {"name": "kitty", "age": 18} # directly declare the dictionary type dict3 = dict ([("name ", "kitty"), ("age", 18)]) # Use the dict function to convert the list to the dictionary dict4 = dict (name = 'Kitty ', age = 18) # Use the dict function to convert the keyword parameter to the dictionary dict5 = {}. fromkeys (["name", "age"]) # Use the fromkeys function to generate a dictionary for the key value list. The corresponding values are None {'age': None, 'name ': none}
 

Basic dictionary operations:

# [Add element] dict1 = {} dict1 ["mykey"] = "hello world" # assign a value directly to a nonexistent key-value pair to add the new element dict1 [('my ', 'key')] = "this key is a tuple" # The dictionary key can be of any inmutable type, for example, numbers, strings, and tuples # [number of key-value pairs] print len (dict1) # [check whether a key exists] print "mykey" in dict1 # True check whether a key value with the key as mykey contains the print "hello" in dict1 # False # [delete] del dict1 ["mykey"] # delete a key-value pair whose key is mykey

Continue to use the above method 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', 'iteritems', 'iterkeys', 'itervalues',  'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues'] 


Dict. clear () delete all elements in the dictionary

Dict. copy () returns a copy of the Dictionary (light copy ).

Dict. get (key, default = None) returns the value of the key in the dictionary dict. If the key does not exist in the dictionary, the value of default is returned. (Note, the default value is None)

Dict. has_key (key) if the key exists in the dictionary, True is returned; otherwise, False is returned. after the in and not in methods are introduced in Python2.2, this method is almost obsolete, but a working interface is still provided.

Dict. items () returns a list of tuples containing Dictionary (key, value) pairs.

Dict. keys () returns a list containing the dictionary's middle keys.

Dict. values () returns a list containing all values in the dictionary.

The dict. iter () method iteritems (), iterkeys (), and itervalues () are the same as their non-iterative methods. The difference is that they return an iterator instead of a list.

Dict. pop (key [, default]) is similar to get (). If the key in the dictionary exists, delete it and return dict [key]. If the key does not exist, the default value is not provided, causing a KeyError.

Dict. setdefault (key, default = None) is similar to the method set (). If the key does not exist in the dictionary, dict [key] = default assigns a value to it.

Dict. setdefault (key, default = None) is similar to the method set (). If the key does not exist in the dictionary, dict [key] = default assigns a value to it.
Boolean Type

Boolean is True and False, which are basically the same as Boolean in other languages. The following lists typical Boolean values.

print bool(0)  #False print bool(1)  #True print bool(-1) #True  print bool([]) #False print bool(()) #False print bool({}) #False print bool('') #False print bool(None) #False 

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.