For large numbers , for example 10000000000
, It's hard to count 0 The number of .Python Allow... In the middle of numbers _
Separate , therefore , It's written in 10_000_000_000
and 10000000000
It's exactly the same . You can also write numbers in hexadecimal 0xa1b2_c3d4
.
Be careful :Python There is no size limit to the integer of , In some languages, integers are limited by their storage length
For large or small floating-point numbers , It must be expressed by scientific counting , hold 10 use e
replace ,1.23x109
Namely 1.23e9
, perhaps 12.3e8
,0.000012
It can be written. 1.2e-5
, wait .
'
Or double quotes "
Any text enclosed , such as 'abc'
,"xyz"
wait . ` Can escape many characters , such as
n Means line break ,
t Represents a tab , character
` We need to escape ourselves , therefore \
The character is ``. r''
Express ''
The internal string does not escape by default . n
It's not easy to read in one line , In order to simplify the ,Python Allowed '''...'''
The format of represents multiline content : print('''line1
line2
line3''')
ord()
Function to get the integer representation of a character ,chr()
Function to convert the encoding to the corresponding character : >>> ord('A')
65
>>> chr(25991)
' writing '
str
How many characters are included , It can be used len()
function , If replaced bytes
,len()
The function counts the number of bytes : >>> len('ABC')
3
>>> len(' chinese ')
2
>>> len(b'ABC')
3
>>> len(b'xe4xb8xadxe6x96x87')
6
>>> len(' chinese '.encode('utf-8'))
6
str
, In memory with Unicode Express , A character corresponds to several bytes . If you want to transmit over the network , Or save to disk , We need to str
Becomes in bytes bytes
.Python Yes bytes
Type of data with b A single or double quotation mark for a prefix indicates , Pay attention to the distinction 'ABC'
and b'ABC'
, The former is str
, Although the content of the latter is the same as that of the former , but bytes
Each character of takes up only one byte . # With Unicode It means str adopt encode() Methods can be encoded as specified bytes
>>> 'ABC'.encode('ascii') # Pure English str It can be used ASCII Encoded as bytes, The content is the same .
b'ABC'
>>> ' chinese '.encode('utf-8') # In Chinese str It can be used UTF-8 Encoded as bytes. stay bytes in , Cannot display as ASCII Byte of character , use x## Show .
b'xe4xb8xadxe6x96x87'
>>> ' chinese '.encode('ascii') # In Chinese str No use ASCII code , Because the scope of Chinese coding exceeds ASCII The range of coding ,Python Will report a mistake .
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
# If we read a byte stream from a network or disk , So the data you read is bytes. To put bytes Turn into str, It needs to be used. decode() Method :
>>> b'ABC'.decode('ascii')
'ABC'
>>> b'xe4xb8xadxe6x96x87'.decode('utf-8')
' chinese '
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
The first line of comment is to tell Linux/OS X System , This is a Python Executable program ,Windows The system ignores this comment ;
The second comment is to tell Python Interpreter , according to UTF-8 Code read source code , otherwise , The Chinese output you write in the source code may be garbled .
4. Null value
Null value is Python A special value in , use None
Express .None
It can't be understood as 0
, because 0
It makes sense , and None
Is a special null value .
stay Python in , Equal sign = It's an assignment statement , You can assign any data type to a variable , The same variable can be assigned repeatedly , And it can be different types of variables . The language with variable type is called dynamic language , It corresponds to static language .
a = 123 # a Is an integer
print(a)
a = 'ABC' # a Change to string
print(a)
# The language with variable type is called dynamic language , It corresponds to static language .
0
At the beginning . -1
Do the index , Get the last element directly , And so on , It can be used -2
、-3
Index to get the penultimate 2 individual 、 Last but not least 3 individual . append()
) Element to end , You can also insert elements (insert()
) To the designated location , For example, the index number is 1 The location of : classmates.append('Adam')
classmates.insert(1, 'Jack')
classmates.pop() # Delete list The element at the end
classmates.pop(1) # Deletes the element at the specified location
append()
、insert()
This way . because tuple immutable , So the code is more secure . If possible , It works tuple Instead of list Try your best tuple.
* tuple The trap of : When you define a tuple when , At the time of definition ,tuple The elements of must be determined . however , To define one, only 1 An element of tuple, A comma must be added `,`, To disambiguate :
t = (1) # The definition is not tuple, yes 1 The number of
t = (1,) # Define a that contains only one element tuple The correct way to write
str Is immutable , and list It's a mutable object .
For mutable objects , such as list, Yes list To operate ,list The internal content will change , such as :
>>> a = ['c', 'b', 'a']
>>> a.sort()
>>> a
['a', 'b', 'c']
And for immutable objects , such as str, Yes str To operate :
>>> a = 'abc'
>>> a.replace('a', 'A')
'Abc'
>>> a
'abc'
Although the string has a replace() Method , And it did change 'Abc', But variables a In the end, it's still 'abc', How to understand ?
For immutable objects , Call any method of the object itself , It doesn't change the content of the object itself . contrary , These methods create new objects and return , such , It ensures that the immutable object itself is immutable .
if
Complete form of statement if < conditional 1>:
< perform 1>
elif < conditional 2>:
< perform 2>
elif < conditional 3>:
< perform 3>
else:
< perform 4>
# Be careful not to write less colons :
input()
Judgment problems caused input()
The data type returned is str
, If you want to use input() Input data to make judgment conditions , You need to convert first ,Python Provides int()
Function will str
Convert to integer , When int()
Function to find that a string is not a legal number, it will report an error .
for x in ...
loop , In turn list or tuple Each element in is substituted into a variable x
, Then execute the indented block statement . avoid key Non existent error , There are two ways :
> * adopt in Judge key Whether there is :
>
> ```python
> >>> 'Thomas' in d
> False
> ```
> * adopt dict Provided `get()` Method , If key non-existent , Can return `None`, Or as you specify value:
>
> ```python
> >>> d.get('Thomas')
> >>> d.get('Thomas', -1)
> -1
> ```
* Delete one key, use `pop(key)` Method , Corresponding value Also from the dict Delete in .
* dict It can be used in many places that need high-speed search , stay Python Almost everywhere in the code , Use... Correctly dict It's very important , The first thing to remember is dict Of key Must be immutable . stay Python in , character string 、 Integers are immutable , therefore , You can do it safely key. and list Is variable , Can't do it key.
2. set
* set and dict similar , It's also a group. key Set , The only difference is set No corresponding... Is stored value.
* set It can be seen as a set of disordered and unrepeatable elements in the sense of Mathematics , therefore , Two set Can do intersection in mathematical sense 、 Operations such as Union .
* To create a set, Need to provide a list As input set :
>>> s = set([1, 2, 3])
>>> s
{1, 2, 3}
add(key)
Method to add elements to set in , adopt remove(key)
Method to delete an element .