strs = 'I like python and java'
one = strs.find('n')
print(one)
two = strs.rfind('n')
print(two)
find It's from the past to the future , Returns the position index of the first character successfully matched
rfind Also looking from the front to the back , But back to The last successful match Position index of the character of
Python in , The syntax of opening the file is
text = oepn(filePath, Mode of operation , Encoding mode )
Common operation modes :
- ‘r’: read
- ‘w’: Write
- ‘a’: Additional
Common coding methods :- utf-8
- gbk
lists = [1, 2, 3, 4, 5, 6]
print(lists[6:])
Pay attention to distinguish slices , Slicing generally refers to creating new objects , Once the slice value of the slice created based on the original list exceeds the index subscript of the original list, it will not be able to get elements from the original list , Therefore, an empty subscript is returned
Slices are light copies , No index is out of bounds
Python The scope of variables follows LEGB principle , namely
- L:Local, Local scope , That is, the variables we define in the function ;
- E:Enclosing, The local scope of the nested parent function , That is, the local scope of the parent function containing this function , But it's not the whole thing ;
- G:Globa, Global variables , Variables defined at the module level ;
- B:Built-in, Variables in the built-in module of the system , such as int, bytearray etc. .
a = [1]
b = 2
c = 1
def fn(lis, obj):
lis.append(b)
obj = obj + 1
return lis, obj
fn(a, c)
print(fn(a, c))
fn(a,c)
: Called once fn function , Now a Turned into [1,2],c still 1, Because although the function returns obj, But there's no assignment , After the function comes out c Or the global variable c;print(fn(a,c))
: Again fn function , The process is the same as above , But when printing, the return value of the function is printed , That is, the formal parameter at this time lis and obj Value , And then lis yes [1,2,2], and obj yes 2.
not 1 and 1
As the result of the stay Python3 in ,
not
Express logical not ,and
Representation logic and , Logic is not (not
) The operation priority of is greater than that of logical and (and
) The priority of the , benot 1
byFalse
, benot 1 and 1
The result isFalse
priority not>and>or, homophonic not at allnot 1 = False
False and 1 = False
str1 = "exam is a example!"
str2 = "exam"
print(str1.find(str2, 7))
stay Python3 in
strs.find(str, beg=0, end=len(strs))
It means thatstrs
Back in First appearancestr
Location subscript of ,beg
It means thatstrs
Start index in , The default is 0( In this question 7),end
End index , The default is strs The length of . But it should be noted that , The returned index is still from 0 At the beginning , Not at allbeg
Value (beg
Just tell the program to start searching from the index of the string ), Therefore, the result of this question is 10
s1 = 'aabbcc'
s2 = 'abc'
count = s1.count(s2)
if count > 0 :
print('s2 yes s1 The string of ')
else:
print('s2 No s1 The string of ')
"""---------------------------"""
s1 = 'aabbcc'
s2 = 'abc'
index = s1.index(s2)
if index > -1:
print('s2 yes s1 The string of ')
else:
print('s2 No s1 The string of ')
"""---------------------------"""
s1 = 'aabbcc'
s2 = 'abc'
find = s1.find(s2)
if find != -1 :
print('s2 yes s1 The string of ')
else:
print('s2 No s1 The string of ')
"""---------------------------"""
s1 = 'aabbcc'
s2 = 'abc'
if s2 in s1:
print('s2 yes s1 The string of ')
else:
print('s2 No s1 The string of ')
The correct answer is B.
count()
The function does not match the object and returns0
index()
The function does not match the object and reports an errorvalue Error
find()
The function does not match the object and returns-1
in
No match to the object returnedFalse
print type(1/2)
- Python2 The middle division defaults to rounding down , therefore
1/2 = 0
, Is an integer .- and Python3 The division in is the normal division , Will keep decimal places , therefore
1/2 = 0.5
, It's floating point (float
).
class A(object):
pass
class B(A):
pass
b = B()
isinstance()
Function to determine whether an object is a known type , similartype()
.issubclass()
Function is used to determine whether the parameter is a subclass of the type parameter .
a = [1,2,3,1,2,4,6]
After weight removal , Get the list b
, Without considering the order of the list elements , The following method is wrong ()b = list(set(a))
"""---------------------------"""
b = {
}
b = list(b.fromkeys(a))
"""---------------------------"""
a.sort()
b = []
i = 0
while i < len(a):
if a[i] not in b:
b.append(a[i])
else:
i += 1
"""---------------------------"""
a.sort()
for i in range(len(a)-1):
if a[i] == a[i+1]:
a.remove(a[i])
else:
continue
b = a
D
The reason for the wrong option is for The number of cycles counted is constant , But as the a Repeated elements are constantly removed , Will cause the list to appear IndexError.
n = 1000
while n > 1:
print(n)
n = n / 2
This question means :n from 1000 Start the cycle , Each cycle executes n = n / 2, It is known that 29 = 512,210 = 1024, Therefore, the number of cycles is 10 Time , When the cycle 10 The cycle condition will not be satisfied after times
sets = {
1, 2, 3, 4, 5}
print(sets[2])
The result of program running is :
python3 in , Collection cannot be indexed , So it will report a mistake :TypeError: ‘set’ object is not subscriptable
Set disorder , No index access
num = 1
def fn():
num += 1
return lambda:print(num)
x = fn()
x()
Although it is declared outside the function num Is a global variable , But if the function body is right num Variable reassignment , As a result, the external global variables are shielded inside the function num, At this point, the statement num += 1 Will throw an exception , namely num Variables are directly referenced without first assigning values .
dicts = {
'one': 1, 'two': 2, 'three': 3}
tmp = dicts.copy()
tmp['one'] = 'abc'
print(dicts)
print(tmp)
Dictionary data type
copy
function , When simple values are replaced , The original dictionary and the copied dictionary do not affect each other , But when you add , Delete and other modification operations , The two will interact .
Therefore, the replacement of values in the new dictionary has no effect on the original dictionary
strs = '123456'
print(strs.find('9'))
find
andrfind
When you can't find it -1index
andrindex
Return when you can't find it value error Therefore, it is recommended to use find
urllib.quote(line.decode("gbk").encode("utf-16"))
Pay attention to the examination , The question is that the decoding order is not the encoding order
def fun(a=(), b=[]):
a += (1, )
b.append(1)
return a, b
fun()
print(fun())
Python The default parameter of is assigned only once when the function is defined , Instead of creating a new reference every time the function is called . It means , When the function definition is complete , The default parameter already has a fixed memory address , If you use a variable default parameter and change it , Then later calls to this function will change this variable object , If the default parameter is an immutable object , There is no such problem , So the correct answer is A Options .
Pay attention to the examination , Two function calls
strs = ['a', 'ab', 'abc', 'python']
y = filter(lambda s: len(s) > 2, strs)
tmp = list(map(lambda s: s.upper(), y))
print(tmp)
filter
The condition in this paper is pass Conditions
filter The output is a filter object , Can passlist
,tuple
Wait for the factory function to convert to the corresponding data type
Python Medium tuple The structure is “ Immutable sequence ”, Use parentheses to indicate . To distinguish between parentheses that indicate priority in Mathematics , When tuple When there is only one element in , You need to add a comma after the element .
dicts = {
'one': 1, 'two': 2, 'three': 3}
print(dicts['one'])
print(dicts['four'])
py3 Access nonexistent indexes or key:
py3 Slice out of bounds ( The index is a natural number ):
''
Null character b = 1
def fn():
nonlocal b
b = b + 1
print(b)
fn()
# ------------------------------------
tup = (('onion', 'apple'), ('tomato', 'pear'))
for _, fruit in tup:
print(fruit)
# ------------------------------------
a = [b for b in range(10) if b % 2 == 0]
print(b) #
# ------------------------------------
lis = [1, 2, 'a', [1, 2]]
set(lis)
- A Options , Variable b Belongs to global variable , So you should use global Declare not nonlocal;
- B Options , have access to _ As placeholder , therefore B Options will not report errors ;
- C Options ,python3.x in , Use list generation , Intermediate variable b Destroyed after generating the list , So use variables again b Will report a mistake ;
- D Options , Collection elements cannot be non hashable objects such as lists , So it will report a mistake .
- A. Function can have no return
- B. look return Multiple values can be returned , But it's not , Multiple values are returned through tuple Realized
- C. stay Python There is no Null This data type , The return should be None
def fn():
t = []
i = 0
while i < 2:
t.append(lambda x: print(i * x, end=","))
i += 1
return t
for f in fn():
f(2)
function
fn
There is a closure phenomenon , The free variable isi
, because python Closures adopt Delay binding , That is, when calling anonymous functions , The cycle is over , herei
The value of is 2, So the output results are 2*2=4, The correct answer is A.
a = '123'
b = '123'
a,b
Is a string immutable type , So point to the same address , thereforea is b
+is Refers to the same address==
Same content===
The content and format are the same
a+b=‘123123’a==123
, Characters and int inequality
strs = ' I like python '
one = strs.strip()
print(one)
two = strs.rstrip()
print(two)
- strip(): Delete leading and trailing spaces ;
- rstrip(): Delete only the right space ;
names = ["Andrea", "Aaslay", "Steven", "Joa"]
lists = []
for name in names:
if name.count('a') >= 2:
lists.append(name)
print(lists)
This question means : Find the letters in the name from the character array of the name ‘a’ The number is greater than or equal to 2 A collection of name lists
First, traverse the character array of names to get each name , Re pass count() Function to determine whether the name contains letters ‘a’ The number is greater than or equal to 2 individual , Store the qualified name characters in lists Array ( We need to pay attention to ‘a’ It's case sensitive ), The last output lists = [‘Aaslay’]
dicts = {
}
dicts[([1, 2])] = 'abc'
print(dicts)
stay Python3 in , Only when all elements in a tuple are immutable , To become a dictionary key, Therefore, errors will be reported during the operation of the program :TypeError: unhashable type: ‘list’
lis = ['apple', 'lemon', 'pear', 'peach']
def fn(x):
return x[::-1]
lis.sort(key=fn, reverse=True)
print(lis)
function
fn
The function of is to reverse the characters , such asfn("apple")
obtain “elppa”. The elements in the list follow fn Function rules , Arrange in descending order , At this time, the list elements pass through the function rules :[‘elppa’,‘nomel’,‘raep’,hcaep], The descending order is as follows :[‘raep’, ‘nomel’, ‘hcaep’, ‘elppa’], But the list elements do not change , So the result is D.
_foo
Can't be used directly for from module import *
__foo
The parser uses _classname__foo
To replace the name , With the same name as other classes __foo__
representative python A special way of marking __foo
Can be used directly from module import *
python There are four main ways of naming :
object
: Common method_object
: Semi protected , Is seen as a “protect”, This means that only class objects and subclass objects can access these variables themselves , Cannot be used outside a module or class , Out-of-servicefrom module import *
Import .__object
To avoid conflicts with subclass method names , The method described for this identifier , Methods of a parent class cannot be easily overridden by methods of a child class , Their names are actually_classname__methodname
.__ object
: All private , Full protection , Private member “private”, This means that only class objects can access , Even subclass objects can't access this data , Out-of-servicefrom module import *
Import .__ object__
: Built in method , Don't define it like this
① In environment variable PYTHONPATH
② Built in module
③python The installation path
④ current path , The perform Python The path of the script file
The group with the correct search order is ()
python The order of searching modules is : Built in module > current path , The perform Python The path of the script file > In environment variable PYTHONPATH>python The installation path , Give a matrix C.
Built in module (built-in) > current path (./) > environment variable > Python The installation path
lis = [1,3,2]
a = id(lis)
lis = sorted(lis)
b = id(lis)
print(a==b)
print("======================")
lis = [1,3,2]
a = id(lis)
lis += [4,5]
b = id(lis)
print(a==b)
print("======================")
tup = (1,3,2)
a = id(tup)
tup += (4,5)
b = id(tup)
print(a==b)
print("======================")
tup = (1,3,2)
a = id(tup)
tup = sorted(tup)
b = id(tup)
print(a==b)
Use
sorted()
Sorting will generate a new sequence , Generated new sequence and original sequence id The value must be different . For mutable objects ,sorted() When sorting, the original sequence also changes , And the subject A of use lis Saved the generated new sequence , therefore AD The output results of options are False; about += operation , If it's a mutable object , Then the sequence before and after the operation id The value remains the same , If it's an immutable object , Then the sequence before and after the operation id Value change , so B correct .
strs = ' I like python '
one = strs.split(' ')
two = strs.strip()
print(one)
print(two)
When there are spaces in the division , Then the space will be reserved when dividing .
a = 1
b = 2
a,b = b,a
print("================")
a,*b,c = range(5)
print(a,b,c)
print("================")
lis = ['1','2']
a,b = list(map(int,lis))
print(a,b)
print("================")
tup = (1,(2,3))
a,b,c = tup
print(a,b,c)
ABCD The program with four options is an iterative element unpacking problem .
- A The option is an elegant way of exchanging two numbers ;
- B Options ,python Allow to use * To handle the remaining parameters ;
- C The option is about unpacking the list , Let the elements of the iteratable object be assigned to the corresponding variables one by one ;
- D Option will throw an exception , This is because the corresponding variable does not satisfy the nested structure of tuples , The correct way of writing should be a,(b,c) = tup
str = "Hello,Python";
suffix = "Python";
print (str.endswith(suffix,2));
str.endswith(suffix[, start[, end]]) Used to determine whether the string ends with the specified suffix , If you return... At the end of the specified suffix True, Otherwise return to False.
Optional parameters "start" And "end" To retrieve the start and end of a string .