Article directory
Python basics review
Second, brush up on the basics of python. Friends who have learned the basics of python, let's deepen their memory together! This will help you avoid bugs when writing code later.
Escapes
- \n: newline
- \t: horizontal tab character
- \r: Overwrite (characters appearing later overwrite previous ones)
- \b: Delete (delete the character before \b, equivalent to backspace on the keyboard)
- : Make two backslashes represent a \ (==Output the above escape character and you can also add one more \ in front. For example
print(“\\n”)
⇒ \Rightarrow ⇒\n)
Example
Cancel“”
Transfer
print("你好\"小杰\"")#想要原样输出带引号的小杰就必须在每个引号前加\或者把外面的引号改成单引号
Unescaping other escapes
Add r in front of the string to cancel the escaping of the entire sentence
print(r"你好\n小杰\n今天有没有加油啊?")
The entire previous sentence is output as is → \rightarrow →Hello\nXiaojie\nHave you cheered today?
not/and/or logical operator precedence
not>and>or
Swap the values of two variables
# 交换
# 法一:中间变量
a = "hello"
b = "world"
c = a
a = b
b = c
print(a,b)
# 法二:python可直接这样操作
a,b = b,a
print(a,b)
Palindromes and slices
a = "山西运煤煤运西山"
b = a[::-1]#切片将a从后往前取 切片:[开始:结尾:步长]列表也可以采用这种方法!
if a==b:
print(f"{
a}是回文")
Common operations on strings
find
Function: Find element position
The first parameter: the string fragment to be found
Second parameter: the starting point to find
If there are multiple string fragments to be searched for, the subscript of the first one is returned.
If not found, return -1
a = "wdfuiewcuhwfwwdw"
print(a.find("w",2,7))
count
Count the number of times a string fragment appears in a string
Not found returns zero
The parameters are the same as find
a = "wdfuiewcuhwfwwdw"
print(a.count("w",2,7))
replace
Function: Replace the specified string fragment
Parameter 1: The string fragment to be replaced
Parameter 2: String fragment after replacement
Parameter three: the number of replacements, from front to back (replace all by default)
a = "wdfuiewcuhwfwwdw"
print(a.replace("w","c",2))
upper()&lower()
How to convert string to uppercase and lowercase
split&strip
split
How to split a string
a = "fwefc,12,123,dew,12w,wdc"
print(a.split(","))#有逗号的地方进行分割得到列表,后面的数字表示切几刀,默认全切
strip
Remove spaces from the beginning and end of the string (the spaces in the middle cannot be removed)
only()
Count string/list length
Common operations on lists
of the
a = [1,2,1]
del a #可以删除整个列表
del a[1]#也可以删除列表中的某个元素
append
Add elements to the list and stuff them all at once
insert
Function: Insert an element into the specified position
The first parameter: the insertion position
Second parameter: inserted content
li = [1,2,3,4]
li.insert(2,9)
print(li)
clear
Clear data from list
remove
- If there are duplicate elements, only the first one is removed
- Parameters are elements
pop
- Remove the last one by default
- Parameters are subscripts
index
- The first parameter is the element
- Second, the three parameters are the starting and ending positions
- Function: Get element subscript
reverse
Function: reverse sorting
a = ["py","c","go"]
a.reverse()
print(a)
extend
- Append data under the original list
- Note: The results of the extend function and list addition are the same, but the extend function will merge another list into the current list (it will not occupy new memory space), while the addition will return a new list (it will occupy new memory space). )
a = [1,2,3]
a.extend([4,5,6])
print(a)
sort
-
Used to sort the list
-
Sort according to ASCII code size rules/number size
-
Data of the same type can be sorted
a = [7,8,3,5] a.sort(reverse=True)#将a逆向排序 print(a)
count
a = [1,2,3,4,7,2,2,2]
num = a.count(2)
print(num)
tuple
- only
- max/min #Find the maximum and minimum according to the ASCII code table
- ==When there is only one piece of data in the tuple, one must be added at the end
,
For example: tuplec = (10,)
- Data is immutable
gather
-
When declared in braces, lists and dictionaries cannot be placed directly
-
Can be used to deduplicate list/tuple/dictionary keys
a = [1,1,2,2,3,3] a = list(set(a)) print(a)#实现列表去重
method
add
Function: add elements
update
Function: Merge collections
a = { 1,2,3,4,5} b = { "g","c","h"} a.add(8) a.update(b) print(a)
remove
Function: Delete elements in the collection. If there is direct deletion, no error will be reported.
pop
Function: Randomly delete elements in the set. If there are no elements in the set, an error will be reported.
discard
Function: Delete elements in the collection. If there is direct deletion, no operation will be performed.
intersection union
s1 = {
1,2,3,5}
s2 = {
12,2,3,1}
s3 = s1 & s2#取交集
s4 = s1 | s2#取并集
print(s3,s4)
dictionary
Add, delete, modify and check
dic = {
"名字":"织梦","年龄":18}#定义字典
dic["技能"] = "python"#增
del dic["名字"]#删
dic["名字"] = "zz"#改
print(dic["名字"])#查
get&keys
dic = {
"名字":"织梦","年龄":18}#定义字典
print(dic.get("名字"))#获取指定键的值
print(dic.keys())#获取所有键
items&values
dic = {
"名字":"织梦","年龄":18}#定义字典
print(dic.items())#获取所有键值对,对字典遍历的时候会用到这种方法
print(dic.values())#获取所有值
clear©
-
clear: clear the dictionary
-
copy: copy dictionary
I pop & drink
dic = {
"名字":"织梦","年龄":18}#定义字典
r = dic.pop("名字")#移除指定键,返回值为值
print(r,dic)
d = dic.popitem()#删除字典中最后一项,并以元组的形式返回该项所对应的键和值
setdefault
dic = {
"名字":"织梦","年龄":18}#定义字典
dic.setdefault("名字","python")#键无则增,有键则忽略
print(dic)
update
dic = {
"名字":"织梦","年龄":18}#定义字典
dic2 = {
"名字":"知梦","擅长":"python"}
dic.update(dic2)#原字典有相应键则改,无则增
print(dic)
judgment
in¬ in
- Determine whether the segment character is in a string/tuple/list/dictionary
- When judging whether it is in the dictionary, you can only judge whether the corresponding key is in the dictionary.
dic = {
"名字":"织梦","年龄":18}
print("名字"in dic)
is&is not
- Numbers/strings/tuples are all immutable data types. If they appear to be the same, they are exactly the same.
- Lists/dictionaries/sets are all mutable data types. If they appear to be the same, they are not actually the same object.
isinstance
- The return value is a bool value
- Syntax: isinstance(a,(int,str,float))
Extract elements from nested lists
a = [1,2,3,[4,5,6],[7,8,9]]
for i in a:
if isinstance(i,list):
for x in i:
print(x)
Function related
variable parameter
-
*args
The types of and**kwargs
are tuple and dictionary respectivelydef test(*args,**kwargs): print(args,kwargs) test(12,x=123)
Unpack
def test(*args):
print(args)
test(*(1,2,3))#解包
a,b,c = (1,2,3)#元组的解包
Parameter order
def test(a,name="小杰",*args,**kwargs):
pass