Python data type

Source: Internet
Author: User

Introduction of data type

(1) Python data types include numeric types, string types, tuples, lists, dictionaries
(2) Numeric type can be divided into integer, Long integer, floating point type, plural type
(3) strings, tuples, and lists are all part of a sequence, and three types can use some of the features of the sequence (such as indexes and slices, and some of the basic operations listed below)

Len ()     # to find the length of the sequence +         # concatenate two sequences *         # repeating sequence elements in        # Determining if an element is in sequence
Not in # Determines whether the element is not in the sequence Max () # returns the maximum min () # Returns the minimum value of CMP (x, y) # to compare two sequences for equality

Second, the value type

1. Integral type

In [1]: a = 123              # defines an integer type in [2]: type (a)              # view data type out[2]: int

-2147483648--2147483647 # Integer value range, if this range is exceeded it becomes a long integer type

2. Long Integer type

123456789123456789123456789    # Definition Long integer in [8]: Type (a)                            # view data type Out[8]: Long in[9]: a                                   123456789123456789123456789L    

3. Floating-point type

In [ten]: A = 1.0    # data type with decimal point is floating point
In [all]: b = 3e+7 # scientific notation also belongs to floating-point type
In [All]: type (a) # view data type out[11]: float

4. Plural type

in [+]: a = 123j    # Letter J is used to identify this is a complex type in []: Type (a)     # view data type out[15]: Complex 

Three, String type

1. Defining strings

' This is a string '        # you can use single quotation marks/double quotes/Three quotation marks to define string type in [+]: str = "This is a string"        # There is no difference between single and double quotes in Python. c5> ' This is a string '    # ' # Three quotes can be written as ' ' or ' ' ', and the three quotes can be used to make annotations in addition to the string types defined  
in [+]: str = "Hello\nworld"    # Single and double quotes if you want to cross-line definition need to add \ n as newline character in []: str = "" "Hello          # Three quotes can be entered directly on the next line   . ..: World "" "

2. Indexing and slicing of strings

in [+]: a = ' ABCDE 'in []: A[0]      # index value starting at 0, representing the first character in the string out[27]: ' A ' in[]: a[1]      # take the second character in the string O UT[28]: ' B 'in []: A[-1]     #-1 for the last character, -2 for the penultimate character, and so on out[29]: ' E 'in [+]: a[0:2] # means taking the first to the third (not package including the third) this range of characters out[30]: ' AB ' in[to]: A[:2] # Zero can be omitted if the ellipsis means starting from the first index to fetch OUT[31]: ' AB ' in[+]: a[1:] # This writes the second to the last index out[32]: ' BCDE ' in[[]: A[-4:-2] # means taking the fourth to the penultimate (excluding the penultimate) the character of this range out[33]: ' BC ' in[34 ]: a[::1] # indicates that every other number is taken once (if it is negative) (from right to left) out[34]: ' ABCDE ' in[out[35]: a[::2] # = Once every two numbers]: ' Ace ' 

3. Methods of strings

 in [1]: a = ' abc '  in [2 ]: A.lower () # lower () used to convert a string to lowercase out[2]: ' abc '  in [3 ]: A.upper () # upper () to convert a string to uppercase Out[3]: ' ABC ' 
in [4]: A.startswith (' ab ' ) # startswith () is used to determine whether to start with the specified character and, if so, to return True, otherwise return falseout[4 ]: True
in [6]: A.isdigit () # isdigit () is used to determine whether the string is a pure number
Out[6]: False

in [7]: a.ca Pitalize () # capitalize () to capitalize the first letter of the string
Out[7]: ' ABC '

in [8]: A.replace (' A ', ' a ') # replace () is used to replace the string, which is replaced by default only once, If you want to replace multiple times you can specify the number of times, such as A.replace (' A ', ' a ', 3)
Out[8]: ' ABC '

in [9]: A.split (' B ') # split () is used to slice the string, in parentheses you can specify the separator, If you do not specify a default space/tab/newline character to slice
Out[9]: [' A ', ' C ']

in [9]: A.find (' B ') # Find () returns the index value of the specified character, or 1
If the character is not found) out[9 ]: 1

in [9]: '-'. Join (a) # join () to generate a new string for the elements in the sequence with the specified character connection, detailed usage Reference rookie tutorial
Out[9]: a-b-c /span>
In [the]: a = ' abc 'in []: A.strip ()            # Strip () to remove the left and right sides of the space out[70]: ' abc ' in[]: A.lstrip ()           # ls Trip () is used to remove the leftmost (left) space out[71]: ' abc ' in[the]: A.rstrip () # Rstrip () to remove the rightmost (right) space out[72]: ' abc ' 
In [the]: name = ' xiaoming '    # Format () usage consistent with Print formatted output string usage in [the]: Age = 21In [PDF]: print (' My name is {0}, my Age was {1} '). Format (name, age)My name was xiaoming, my age is  

4. String module

In [1]: Import string in[2]: string.lowercase                     # string. Lowercase used to print all lowercase letters out[2]: ' ABCDEFGHIJKLMNOPQRSTUVWXYZ ' in[3]: string.uppercase                     # string. Uppercase used to print all uppercase letters OUT[3]: ' ABCDEFGHIJKLMNOPQRSTUVWXYZ ' in[4]: string.capitalize (' hello ')           # string. Capitalize () specifies the first letter of the string to capitalize out[4 ]: ' Hello ' in[5]: string.replace (' Hello ', ' h ', ' H ') # string. Replace () replaces string out[5]: ' Hello ' /c6>   

Iv. List

1. Basic operation of the list

in [+]: a = [' abc ', 123, 456]    # Create List in [$]: a[0] = ' def '             # Modify list element in [Update]: type (a)                  # view data type In [the]: del a                    # delete list
In []: del a[0] # Delete an element of the list

2. How to List

In [a]: a = [' A ', ' B ', ' C ']in []: A.append (' d ')        # append () is used to append the specified list element

In []: A.remove (' d ') # Remove () is used to delete the specified list element, and if there are multiple identical list elements, the default is to delete only one

In [All]: A.insert (2, ' C ') # Insert () inserts the element in front of the specified index, which means inserting the character ' C ' before the index is 2 (i.e. ' C '), the result is [' A ', ' B ', ' C ', ' C ']

In [All]: A.index (' B ') # Index () returns the index value of the specified element

In [the]: A.sort () # Sort () to sort the list (forward sort)

in [+]: A.reverse () # reverse () is used to reverse the list element, such as a = [' A ', ' B ', ' C '], then the a.reverse () result is [' C ', ' B ', ' a ']

In [the]: A.pop (2) # Pop () is used to return and delete the element at the specified index, and if you do not specify an index value, the default is to return and delete the last

In [Bayi]: A.extend (Range (5)) # Extend () is used to append an iterative object to the list, and a range (5) in parentheses is an iterative object that is typically used to append the contents of one list to another list of five, tuples

Five, the tuple

1. Introduction to Tuples

(1) Tuples are defined by parentheses and can store a series of values
(2) Tuples are immutable like strings, meaning that when you define a tuple, you cannot change the value of an element unless you redefine the entire tuple
(3) Tuples are typically used when a user-defined function can safely take a set of values, that is, the value of the tuple being used does not change

in [[]: t = (' abc ', 123, 456)    # define Tuples
in [[]: t = (' abc ',) # when there is only one element in the tuple followed by a comma, otherwise python will assume that this is a string type rather than a tuple type
In [Wuyi]: type (t) # View data type out[51]: tuple

2. Tuple methods

in [+]: t = (' A ', ' B ', ' C ', ' A ', ' a ') in [the]: T.count (' a ')    # count () counts the number of elements out[57]: 3 in[up]: T.index (' B ')    # Index () returns the indexed value corresponding to the element out[59]: 1

VI. Dictionary

1. Introduction to the Dictionary

(1) Dictionary is the only type of mapping in Python (key-value)
(2) The value of the dictionary is mutable, but the key of the dictionary is immutable and key is unique and cannot have duplicate key values

In [1]: a = {1: ' A ', 2: ' B ', 3: ' C '}    # definition dictionary in [2]: type (a)    # view data type out[2]: dict

In [3]: a[2] # Access dictionary elements based on key
OUT[3]: ' B '

2. The method of the dictionary

In [4]: a = {1: ' A ', 2: ' B ', 3: ' C '}in [5]: A.keys () # keys () is used to return all keyout[5 in the dictionary]: [1, 2, 3 ]in [6 ]: a.values () # values () used to return all valueout[6 in the dictionary]: [' A ', ' B ', ' C ' ]in [7]: A.get (2) # get () returns the value of the specified key, which returns the value of key 2  out[7]: ' B '  
in [8]: A.has_key (1 ) # Has_key () used to convict The specified key value is out[8 ]: Truein [9]: A.items () # items () is used to return the key- value pair in the dictionary as a tuple, and the outer layer is a list that can be iterated through the dictionary out [9]: [(1, ' a '), (2, ' B '), (3, ' C ' )]
in []: A.iteritems () # Iteritems () is used in line with items (), but returns an iterator that does not consume memory, only when needed Called, just like the relationship between print and return
Out[10]: <dictionary-itemiterator at 0x297ac58>
in [all]: A.copy () # Copy () is equivalent to a copy dictionary, It is generally assigned to a variable, such as B = a.copy () out[11]: {1: ' A ', 2: ' B ', 3: ' C ' }in []: A.pop (2 ) # Pop () is used to return and delete the element corresponding to the specified key Vegetarian out[12]: ' B '

in []: A.update (b) # Update () is used to merge two dictionaries, such as a = {1: ' A '}, B = {2: ' B '}, then the result of A.update (b) is {1: ' A ', 2: ' B '}
in [+]: A.clear () # Clear () clears all elements in the dictionary
In [PNS]: a = {1: ' A ', 2: ' B ', 3: ' C '} in    []: A.setdefault (2)          # SetDefault () function is consistent with get (), used to return the value of the specified key Value, of course, if key exists in the case of out[38]: ' B ' in[Max]: A.setdefault (4, ' d ')     # Returns the default value we set and appends key-value to the dictionary when the specified key does not exist out[ []: ' d ' in[:aout[47]: {1: ' A ', 2: ' B ', 3: ' C ', 4: ' d '}     

Python data type

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.