- List and tuple operations
- String manipulation
- dictionary operations
- Collection operations
- file operations
- Operation
(ps: I didn't save what I wrote yesterday... I want to cry, so the code demonstration part of what I wrote today is copied directly from others in order to save time)
1. List and tuple operations
1.1, list operation
List initialization:
names = ['Alex',"Tenglan",'Eric']
Slicing of the list: (closed left and open right, small in front and large in back)
>>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"] >>> names[1:4] #Take the numbers between subscript 1 and subscript 4, including 1, excluding 4 ['Tenglan', 'Eric', 'Rain'] >>> names[1:-1] #Remove the value of subscript 1 to -1, excluding -1 ['Tenglan', 'Eric', 'Rain', 'Tom'] >>> names[0:3] ['Alex', 'Tenglan', 'Eric'] >>> names[:3] #If it is taken from the beginning, 0 can be ignored, the same effect as the previous sentence ['Alex', 'Tenglan', 'Eric'] >>> names[3:] #If you want to take the last one, you must not write -1, you can only write like this ['Rain', 'Tom', 'Amy'] >>> names[3:-1] #This way -1 will not be included ['Rain', 'Tom'] >>> names[0::2] #The following 2 is the representative, every other element, take one ['Alex', 'Eric', 'Tom'] >>> names[::2] #Same as the previous sentence ['Alex', 'Eric', 'Tom']
Addition of a list (append + insert):
>>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy'] >>> names.append("I'm new here") >>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', 'I'm new here'] >>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', 'I'm new here'] >>> names.insert(2, "Forcibly insert from the front of Eric") >>> names ['Alex', 'Tenglan', 'Forcibly inserted before Eric', 'Eric', 'Rain', 'Tom', 'Amy', 'I'm new here']
List deletion (pop, del, remove):
>>> del names[2] >>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Insert after eric and try a new pose', 'Tom', 'Amy', 'I'm new here'] >>> del names[4] >>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', 'I'm new here'] >>> >>> names.remove("Eric") #Remove the specified element >>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 'I'm new here'] >>> names.pop() #delete the last value of the list 'I am new here' >>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']
Changes to the list:
>>> names ['Alex', 'Tenglan', 'Forcibly insert in front of Eric', 'Eric', 'Rain', 'Insert after eric and try a new pose', 'Tom', 'Amy', 'I'm new here '] >>> names[2] = "Time to replace" >>> names ['Alex', 'Tenglan', 'It's time for a substitution', 'Eric', 'Rain', 'Insert after eric and try a new pose', 'Tom', 'Amy', 'I'm new here' ]
List lookup: (for in..,index)
>>> names ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1'] >>> names.index("Amy") 2 #Only return the first subscript found
Expansion of the list:
>>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy'] >>> b = [1,2,3] >>> names.extend(b) >>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
Statistics for the list:
>>> names ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3] >>> names.count("Amy") 2
Copy of list (shallow copy + deep copy):
No
1.2, tuple operation
Tuples are similar to lists, but they are not allowed to be modified, represented by ()
names = ("alex","jack","eric")
Tuples cannot be modified, so there are only two methods: count and index
2. String manipulation
Note: No matter what method is used, the string itself will not be modified
Common operations on strings:
name.capitalize() capitalize the first letter name.casefold() uppercase all lowercase name.center(50,"-") outputs '---------------------Alex Li--------------- -------' name.count('lex') counts the number of occurrences of lex name.encode() encodes the string into bytes format name.endswith("Li") determines whether the string ends with Li "Alex\tLi".expandtabs(10) output 'Alex Li', convert \t to how long a space name.find('A') Find A, return its index if found, return -1 if not found format : >>> msg = "my name is {}, and age is {}" >>> msg.format("alex",22) 'my name is alex, and age is 22' >>> msg = "my name is {1}, and age is {0}" >>> msg.format("alex",22) 'my name is 22, and age is alex' >>> msg = "my name is {name}, and age is {age}" >>> msg.format(age=22,name="ale") 'my name is ale, and age is 22' format_map >>> msg.format_map({'name':'alex','age':22}) 'my name is alex, and age is 22' msg.index('a') returns the index of the string where a is located '9aA'.isalnum() True '9'.isdigit() is an integer name.isnumeric name.isprintable name.isspace name.istitle name.isupper "|".join(['alex','jack','rain']) 'alex|jack|rain'
Three, dictionary operation
Dictionary definition:
info = { 'stu1101': "TengLan Wu", 'stu1102': "LongZe Luola", 'stu1103': "XiaoZe Maliya", }
Features of the dictionary:
- disorder
- key must be unique
Addition of the dictionary:
>>> info["stu1104"] = "苍井空" >>> info {'stu1102': 'LongZe Luola', 'stu1104': 'Aoi Sora', 'stu1103': 'XiaoZe Maliya', 'stu1101': 'TengLan Wu'}
Dictionary deletion: pop, del
>>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': 'Mutolan'} >>> info.pop("stu1101") #Standard delete pose 'Mutolan' >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} >>> del info['stu1103'] #Change posture to delete >>> info {'stu1102': 'LongZe Luola'}
Changes to the dictionary:
>>> info['stu1101'] = "Mutolan" >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': 'Mutolan'}
Dictionary lookup:
>>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} >>> >>> "stu1102" in info #Standard usage True >>> info.get("stu1102") #Get 'LongZe Luola' >>> info["stu1102"] #Same as above, but see below 'LongZe Luola' >>> info["stu1105"] #If a key does not exist, it will report an error, get will not, it will return None if it does not exist Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'stu1105'
Looping over dictionaries:
#method 1 for key in info: print(key,info[key]) #Method 2 for k,v in info.items(): #The dict will be converted into a list first, don't use it when the data is large print (k, v)
Fourth, the collection operation
collection set, unordered, non-repeating
Common operations:
s = set([3,5,9,10]) #Create a set of values t = set("Hello") #create a set of unique characters a = t | s # union of t and s b = t & s # intersection of t and s c = t – s # find the difference (terms in t but not in s) d = t ^ s # symmetric difference (term in t or s, but not both) Basic operation: t.add('x') # add an item s.update([10,37,42]) # Add multiple items in s Use remove() to remove an item: t.remove('H') len (s) length of set x in s test if x is a member of s x not in s test if x is not a member of s s.issubset(t) s <= t test if every element in s is in t s.issuperset(t) s >= t test if every element in t is in s s.union(t) s | t returns a new set containing each element in s and t s.intersection(t) s & t returns a new set containing the common elements of s and t s.difference(t) s - t returns a new set containing the elements in s but not in t s.symmetric_difference(t) s ^ t Returns a new set containing the unique elements of s and t s.copy() returns a shallow copy of set "s"
Five, file operation
The basic operation process of the file:
- Open the file, get the file handle and assign it to a variable
- By operating on file handles
- close file
Basic operation:
f = open('lyrics') #Open the file first_line = f.readline() print('first line:',first_line) #Read a line print('I am the separator'.center(50,'-')) data = f.read()# Read all the rest, don't use it when the file is large print(data) # print file f.close() #Close the file
readline() is to read a line, read() is to read all
File open mode:
- r, read-only mode
- w, write-only mode (unreadable!!!! Note that in this mode, if there is already a file with the same name, a new file will be created to overwrite the original file, causing the original file to be emptied)
- a, append mode (unreadable!! Compared with w, it will directly append content to the original file of the same name)
- r+ (read and write)
- w+ (writable and readable, but the above problem still exists when the file is opened first)
- a+(a)
6. Homework
- Realization of three-level menu
- Shopping cart optimization
- Implement a simple shell sed replacement function
- Modify the haproxy configuration file