Recently, I will sort out the basic knowledge of Python. This is the first one. Xiaobai is just getting started, so please correct me if there are any errors or inaccuracies.
Alibaba Cloud Simple Application Server: Anti COVID-19 SME Enablement Program
$300 coupon package for all new SMEs and a $500 coupon for paying customers.
Let's first list the basic data types provided by Python: numeric values (integer, floating-point, complex, boolean, etc.), strings, lists, tuples, dictionaries, sets, etc. They are simply classified as follows:
Numbers
numbers: lists some simple examples
361, -361, 0, 66666 # Integer --> int()
3.61, 3.14e-6, 0.0 # Floating point type --> float()
3+6j, 3.0+6.0j, 6j # complex number --> complex([real[, imag]])
0b101010 # Binary --> bin()
0o177 # octal --> oct()
0x9ff # Hexadecimal --> hex()
# Common operations
+, -, *, /, //, %, ** # / The result is a floating point number, // the result is only the integer part
&, |, ^, <<, >> # bit operation, and, or, exclusive or, shift left, shift right
bool: Call bool() to check the true or false value of the variable, True or False.
The if statement controls the execution path of the program by judging the Boolean type. At the same time, the data in Python has implicit true and false values, which can make the code shorter and more effective.
String
First, we define a s='python' statement. Its execution sequence in the computer is to first create a string python in memory, create a variable s in the program stack register, and finally assign the address of python to s.
Let's take a look at some common operations of strings
"""String""" # Multi-line string, generally used for file descriptions and function descriptions, and can be output using __doc__
s ='elegant Python'
# Slice
s[0], s[-1], s[3:], s[::-1] #'优','n','Python','nohtyP的雅优'
# Replace, you can also use regular expressions to replace
s.replace('Python','Java') #'elegant Java'
# Find, find(), index(), rfind(), rindex()
s.find('P') # 3, returns the subscript of the first occurrence of the substring
s.find('h', 2) # 6, set subscript 2 to start searching
s.find('23333') # -1, return -1 if not found
s.index('y') # 4, returns the index of the first occurrence of the substring
s.index('23333') # Different from find(), an exception will be thrown if it is not found
# Convert case, upper(), lower(), swapcase(), capitalize(), istitle(), isupper(), islower()
s.upper() #'elegant PYTHON'
s.swapcase() #'elegant pYTHON', case swap
s.istitle() # True
s.islower() # False
# Go to the space, strip(), lstrip(), rstrip()
# Format
s1 ='%s %s'% ('Windrivder', 21) #'Windrivder 21'
s2 ='{}, {}'.format(21,'Windridver') # It is recommended to use format to format strings
s3 ='{0}, {1}, {0}'.format('Windrivder', 21)
s4 ='{name}: {age}'.format(age=21, name='Windrivder')
# Connection and segmentation, use + connection string, each operation will recalculate, open up, and release memory, which is very inefficient, so it is recommended to use join
l = ['2017', '03', '29', '22:00']
s5 ='-'.join(l) # '2017-03-29-22:00'
s6 = s5.split('-') # ['2017', '03', '29', '22:00']
# There are some commonly used ones, only listed here
S.endswith() # Whether the string ends with the given string
S.startswith() # Whether the string starts with the given string
S.isalnum() # Are all letters and numbers
S.isalpha() # Are all letters
S.isspace() # Are all whitespace characters
S.center(width, [fillchar]) # center alignment
S.ljust(width,[fillchar]) # Left justify, default is space completion
S.rjust(width,[fillchar]) # align right
S.count(substr, [start, [end]])# Count the number of occurrences of substr in S
S.splitlines([keepends]) # Split lines into lists, keepends is a bool value, if true, line separators will be retained after each line.
The above are some common operations. Of course, there is one that is not listed. I want to talk about it separately, which is the encoding of
Python3 strings:
1. ASCII encoding appeared the earliest, with only 127 characters such as uppercase and lowercase English letters, numbers and some symbols. In order to achieve multilingual representation, such as Chinese GB2312 encoding, Japanese Shift_JIS encoding, etc., Unicode was born, and it unified all languages to A set of codes;
2. In Python3, all strings are stored in Unicode in memory;
3. When it is necessary to save files to peripherals or for network transmission, it is necessary to perform encoding conversion and convert characters to bytes to improve efficiency
# encode Convert characters to bytes
>>> str ='elegant Python'
>>> str.encode() # The default encoding is UTF-8
b'\xe4\xbc\x98\xe9\x9b\x85\xe7\x9a\x84Python'
>>> str.encode('gbk')
b'\xd3\xc5\xd1\xc5\xb5\xc4Python'
# decode Convert bytes to characters
>>> b'\xe4\xbc\x98\xe9\x9b\x85\xe7\x9a\x84Python'.decode()
'Elegant Python'
>>> b'\xd3\xc5\xd1\xc5\xb5\xc4Python'.decode('gbk')
'Elegant Python'
In Python3, Unicode characters in memory are represented by str objects. Correspondingly, Python3 uses a new data type to represent bytes, which is bytes, so the byte stream after encode conversion is not a str object, but bytes bytes object, of course, it supports operations such as fragmentation, indexing, and basic numerical operations, but data of str and bytes type cannot perform + operations.
Take a look at the definition of the bytes data type:
>>> byt = b'elegant Python'
File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
>>> byt = b'Python'
>>> type(byt)
<class'bytes'>
From the above example, we can see that the bytes object cannot be composed of characters beyond the ASCII code range, and only accepts characters in the ASCII code range.
>>> u'a'
'a'
>>>'\u0061'
'a'
>>>'中'.encode('unicode-escape')
b'\\u4e2d'
>>> b'@Aa'
b'@Aa'
>>> b'\x40\x41\x61'
b'@Aa'
>>> #-*- coding: utf-8 -*-
...
>>>
Similarly, from the above example, we can also summarize some cheating things:
Unicode code has two representations in Python3, u'string' and \u four-digit hexadecimal number; distinguishing r'string' is the original string that is not escaped
Save the characters directly in Unicode code using unicode-escape
In the interactive environment of Python, when outputting bytes object, it can be represented by ASCII code or represented by hexadecimal \x
Declaring #-*- coding: utf-8 -*- in the Python header tells the Python compiler to read in utf-8. This declaration does not save the Python file itself as utf-8. At this time, you need to use text The editor saves the file encoding.
That’s all for my understanding of the coding part. I still feel that I haven’t summarized the coding problems clearly (helpless). I look forward to your explanation.
List
Python can use syntactic sugar [] to represent a list, where the elements can be of any type, and the data is stored dynamically in a sequential storage method:
# Definition
L = [] # Recommended way
L = list()
L = ['Windrivder', 21, {'name':'xiaoming'}]
# Multiple assignment skills
name, age, other = L
# List slice reference str
# Common methods
L.append('a') # ['Windrivder', 21, {'name':'xiaoming'},'a']
L.pop() # ['Windrivder', 21, {'name':'xiaoming'}], you can also specify the subscript to delete elements
L.extend(L1) # merge list L1
L.insert(1,'a') # Insert'a' at the position of subscript 1
L.index('a') # index() of the same string
L.remove('a') # delete operation
L.count('a') # Find the number of a certain value
L.reverse() # reverse
L = [2, 4, -1, 9, -5, 6]
L.sort() # sort() sorting, very flexible to use
L.sort(reverse=True) # reverse order
L.sort(key=abs) # Pass in the function key as the sorting rule
for l1, l2 in zip(['windrivder', 21], ['jack', 22]): # zip traverse two lists at the same time
print('{} --> {}'.format(l1, l2))
for index, value in enumerate(L): # enumerate traverse the list with index
print('{} --> {}'.format(index, value))
# List generation
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
r = [sum(L) for l in L] # [6, 15, 24]
L = [a for a in range(0, 10) if a% 2 == 0] # [0, 2, 4, 6, 8]
Tuple
The difference between tuples and lists is that tuples are immutable, and the elements cannot be modified, but the memory can clearly know how much space needs to be allocated to the tuple
# Definition
t = ()
t = tuple()
t = (1,) # When defining an element, it needs to be distinguished from (1)-->int
t = ('Windrivder', 21, {'name':'xiaoming'})
# No more methods are listed, you can use tuple.__dir__() to view
t.index(21) # 1