Deep understanding of basic data types in Python __python

Source: Internet
Author: User

Blog Core content:

1, the concept of the system, coding, decoding
2. Concepts related to classes and objects
3, the basic type of string function introduction
4, the basic type of integral type function introduction
5. Introduction to Boolean types of basic types
6, the basic type of list type introduction
7. Introduction to Range and enumerate usage
8, the basic type of tuple type introduction
9, the basic type of Dict dictionary type Introduction
10, the basic type of set set type introduction
11. List-generation in Python

1, the concept of the system, coding, decoding

The focus of this blog is on the basic data types in Python, but the beginning of the article begins by introducing the concepts of introduction, encoding, and decoding.
The so-called n into the system is every n into 1, so the binary system is every 2 into the 1,8 into the system is every 8 into the 1,16 is every 16 into 1, for the relationship between the different systems, we just have to remember a word can be: The number is the essence of the system is only a different form of expression , the following is commonly used in the system comparison table.

As shown in the figure above:
The relationship between bits and octal bits, hexadecimal digits: A 8-bit is represented by 3 bits, and a 16-bit is represented by 4 bits.
For a piece of code:

Value = Ten
print ("Decimal representation of 10:%d"% value)
print ("10 octal bit representation:%o"% value)
print ("hexadecimal in-place representation of 10:%x"% Value

Run Result:

Decimal representation of 10: The octal bit representation of ten
10:
hexadecimal representation of 10: A

Through the above procedures, it is easy to understand that the system is only a different manifestation of the number.
For our computer, only 0 or 1 can be identified, that is, the so-called binary, the computer stored in any data at the bottom of the computer are 0 or one to store, but the same data, the specified encoding format is different, stored in the computer binary form is not the same. For example, the same Chinese character, if the corresponding encoding format is utf-8, then the Chinese character will correspond to 3 bytes (i.e. 24 bits) at the bottom of the computer storage, if the corresponding encoding format of the Chinese character is GBK, The Chinese character will then be stored at the bottom of the computer with 2 bytes (16 bits).
The purpose of our programming is to get the computer to work, and the result of programming is simply a bunch of characters, which means that what we're programmed to accomplish is: a bunch of characters driving a computer to work, so you have to go through a process:
Character--– (translation process) ——-> numbers
This process is actually a standard for how a character corresponds to a particular number, which is called a character encoding.
The concept of character encoding: that is, a character in the bottom of the calculation in exactly what kind of binary form to store, such as our common ASCII, UTF-8, GBK encoding and so on . The so-called decoding is a data in which format to parse, so the character of the local file in which encoding format to store, we should use which encoding format to parse the file, and then avoid the problem of garbled.
To make it easy for everyone to understand, the following is an example of the concept of system, encoding, and decoding.

From the schematic above, we see: Our data is stored in binary form at the bottom of the computer (it can be stored in a number of coded formats), and when we read the file we get the first 0, 1 strings, and then parse the corresponding data in the specified encoding format.
So how do we get 01 of a file in Python, and here's the code example where RB represents opening the file in binary form and reading the content. (Note: In the result we see 01 strings in the form of 16)

F1 = open ("DB", "RB")
data = F1.read ()
print (data)

Run Result:

B ' lijie\xe6\x9d\x8e\xe6\x9d\xb0 '

So our operation of the file is essentially based on the encoding of the operation of the file.
Specific details: http://blog.csdn.net/a2011480169/article/details/71250396
Details of the encoding: http://blog.csdn.net/a2011480169/article/details/54344632

2. Concepts related to classes and objects

Some of the basic types we use in Python include: string str, integer int, list lists, and dictionary dict, to give you a clearer idea of the nature of these types, let's first introduce two concepts: classes and objects.
1> the concept of combining static attributes of a class of things with dynamically enforceable operations is a class
An individual of the 2> class is the object, the object is concrete, the real thing.

So, we often say that str, int, dict, and list are essentially classes, and the specific strings we create, the exact integers, the specific dictionaries, and the lists are actually objects constructed by the class.

3, the basic type of string function introduction

This refers to the concepts of classes and objects in which the Str string class is undoubtedly the most important class, the Str class object represents an immutable encoding string, and the Str class object cannot be changed once it is created, that is, whenever a string is created, a chunk of the memory space is redistributed. Therefore, if the content of the string is often modified to use the Str class, it will cause memory space and waste of time, in simple words,STR class objects are not modifiable .
The following methods commonly used in the STR class are listed below:






The 44 methods that are often used in the above list contain 11:

Here's a partial code example:

Name = "Alexericalex" Print (Name.upper ()) print (Name.lower ()) print (
name.split ("E"))
print ( Name.find ("E")) print (
name.strip ()) Print (
name.startswith ("Al")) Print (
name.endswith ("ex"
)) Print (Name.replace ("Ex", "Ex"))

value = "Lijie"
print ("A Chinese character corresponds to a utf-8 encoding format that corresponds to 3 bytes, as follows:")
print ( Value.encode (encoding= "Utf-8"))

user_info = "My name is: {0}, my name is: {1}"
Print (User_info.format ("Alex", 25))

user_info_list = ["Alex", "123123", "1"]
print ("* * *". Join (User_info_list))

Run Result:

Alexericalex 
 alexericalex 
[' Alex ', ' Ricalex ']
3
Alexericalex
false
 Alexericalex 
a Chinese character corresponding to the UTF-8 encoding format corresponds to 3 bytes, as follows:
B ' \xe6\x9d\x8e\xe6\x9d\xb0 '
My name is: Alex, my name is:
Alex****123123****1

In addition, there are some additional methods in the Str class:

Here no longer superfluous elaboration.

4, the basic type of integral type function introduction

Here are some common methods for int types, which are much less than STR types.

Related programs:

num =
print ("convert int variable 15 to corresponding bit:") print (
bin (num)) print
(the minimum number of bits for integer number 15 in binary notation: ")
print ( Num.bit_length ())
print ("Get the byte representation of the current number 15:")
print (num.to_bytes (1, "big")

Run Result:

Converts the INT variable 15 to the corresponding bit representation:
0b1111
The minimum number of bits for the integer number 15 in binary notation:
4
Gets the byte of the current number 15:
B ' \x0f '
5. Introduction of Boolean function of basic type

Among the basic types, the Boolean type is the simplest. The numeric values of a Boolean type are divided into two types: true and False, with the following points to be remembered:

program Example:

User_list = ""
if User_list:
    print ("Hello")
else:
    Pass

In the above program, if the value of User_list is true, then print hello, otherwise no processing, because the value of user_list is null, so the Boolean value is False, so this program does not do any processing.

6, the Basic Type list function introduction

Before we introduce the list of methods, let's introduce the concept of the container, because the list is essentially a container. In Python, if a class is designed to hold objects of other classes, this class is called a container, or a collection, a whole that is formed by grouping together objects of the same or similar nature.
List lists: Because of the internal storage structure, the order of elements is distinguished in the list collection, and it allows duplicate elements to be included. The elements in the list collection correspond to the ordinal of an integer to the position of the container, and the elements in the container can be accessed according to the ordinal, and the elements in the container can be duplicated. The list column represents a Mutable object .
The following list of common methods is listed below:


Code Part example:

Li = ["Alex", "Eric", "Rain", "Dongdong", "Youyou"]
print ("Remove Eric from List:")
Li.remove ("Eric")
print (LI)
print ("Deletes the object from the second position in the list and returns its value:")
value = Li.pop (1) print (
value) print (
li) print
(" Delete elements from the first and second positions in the list: ")
del Li[0:2]
print (LI)

Run Result:

Remove Eric from the list:
[' Alex ', ' rain ', ' dongdong ', ' youyou ']
deletes the object from the second position in the list and returns its value:
rain
[' Alex ', ' Dongdong ', ' youyou ']
deletes elements from the first and second positions in the list:
[' Youyou ']
7. Introduction to Range and enumerate usage

The two functions, range () and enumerate (), are used in a number of situations, as shown in the following example:

Range () Part of the code example:

Li = ["Alex", "Eric", "Rain", "Dongdong", "Youyou"] for the
Index in range (0, Len (LI)):
    print (Index,li[index])

Run Result:

0 Alex
1 Eric
2 rain
3 Dongdong
4 Youyou

Enumerate () Part of the code example:

Li = ["Alex", "Eric", "Rain", "Dongdong", "Youyou"] for
Key,value in Enumerate (li,1):
    print (Key,value)
index = input ("Please enter your chosen teacher:")
index = INT (index)
print (li[index-1])

Run Result:

1 Alex
2 Eric
3 rain
4 dongdong
5 youyou
Please enter your choice of teacher: 2
Eric
8. Introduction to the type of meta group of the basic type

When I was in the process of learning Scala, I had already come into contact with the Meta group, the relevant concept of the tuple in Scala:
(1) A lot of data can be stored in the tuple, and the access of the data in the tuple starts from subscript 1.
(2) Tuples are important because, for a function or operator, it is possible to return several values, and we commonly use several variables defined in tuple to accept
The value returned by the function.
Unlike Scala, the following table of tuples in Python starts with subscript 0, the related concept of the tuple in Python:
(1) The tuple is a special list, after the elements in the tuple have been created, they can no longer be changed, that is, the elements in the tuple cannot be added, cannot be deleted, cannot
Update, the tuple is a class object (set) that cannot be modified, that is, immutable.
(2) after the last element in the tuple, remember to add a comma. (Unspoken rules)
The methods commonly used in tuples are summarized as follows:

Partial code Examples:

User_tuple = ("Alex", "123123", ["TV", "eating", "swimmng"],3,)
user_tuple[2][2] = "Shopping"
print (user_tuple )

Run Result:

(' Alex ', ' 123123 ', [' TV ', ' eating ', ' shopping '], 3)

But let's note that the following example is wrong:

User_tuple = ("Alex", "123123", ("TV", "eating", "swimmng"), 3,)
user_tuple[2][2] = "shopping"

user_tuple = (" Alex "," 123123 ", (" TV "," eating "," swimmng "), 3,)
user_tuple[2] = (" Eric "," 123123 ", 4)

Two types of writing to the following will be an error:

TypeError: ' Tuple ' object does not support item assignment

A tuple is, in the final analysis, an immutable class object instance.

9, the basic type of dictionary type of introduction

Here's another container, the dictionary in Python, the dictionary in Python is similar to a map map in Java, at least in effect I think it's the same, here's the concept of mapping map in Java:
Map maps: Because of the internal storage structure, mappings cannot contain duplicate key values, each key can map at most one value, or there will be overlay, map is a set of key objects and value objects mapping, that is, the map container to both store the data itself, but also to store the keyword.
The dict in Python itself is a mutable object, and its commonly used methods are as follows:



Some examples of code features:

User_info = {
    "name": "Alex",
    "pass_wd": "123123",
    "Times": 1
}
print ("Get the corresponding value value based on key:")
value1 = user_info.get ("name")
print (value1) print ("Delete value value for
a key and get its value")
value2 = User_ Info.pop ("name") print (
value2) print (
user_info) print (
add a key value pair to the list)
User_info.setdefault ( "Passison", "singing")
print (User_info)

Run Result:

Gets the corresponding value value based on key:
Alex Deletes the value
of a key corresponding to it and gets its value
Alex
{' pass_wd ': ' 123123 ', ' Times ': 1}
Adds a key value to the list to
{' pass_wd ': ' 123123 ', ' Times ': 1, ' Passison ': ' Singing '}
10. Introduction of set type of basic type

Set collections: Because of the internal storage structure, the set set does not distinguish between elements in order, and duplicate elements are not allowed, and the set container can correspond to the concept of set in mathematics, and the same elements are not added.
Common methods for set collections are described:



Partial code Examples:

User_info1 = {"Alex", "123123", 1}
User_info2 = {"Alex", "123123", 2}
print ("S1 contains elements not contained in S2:")
User_info3 = User_info1.difference (User_info2) print (
User_info3)
print ("S1 contains elements not contained in S2, S2 contains elements not contained in S1:")
User_info4 = User_info1.symmetric_difference (User_info2)
print (USER_INFO4)

Run Result:

S1 contains elements not contained in S2:
{1}
S1 contains elements not contained in S2, S2 contains elements not contained in S1:
{1, 2}
11. List-generation in Python
#!/usr/bin/python
#-*-coding:utf-8-*-


#列表生成的方式1

user_list = [] for
item in range (Ten):
    user_ List.append (item)
Print (user_list)

#列表生成的方式2
user_list2 = ['%s '%i for-I in range ()]
print (user_ LIST2)

#列表生成式
user_list3 = [I for I in range (Ten) if I > 5]
print (user_list3)


user_list4 = [I for I In range if i>3 and I <
print (USER_LIST4)

#if的后面不能加else

Run Result:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']
[6, 7, 8, 9]
[4, 5, 6, 7, 8, 9]

Process finished with exit code 0

Ok,python The basic data types are introduced here, if there is a problem, please comment.

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.