Relevant:
- Character string
- Common functions (refer to function libraries in more detail or note tips when using compilers)
- String Formatting
- Original string
- list
- Common Functions
- List Generation
- Dictionaries
- Common Functions
- aggregate
- Common Functions
Additional:
Many of python's compilers provide code completion and prompting when filling in parameters
Character string
1. Common functions:
Strings are immutable objects and methods of strings do not change the data of the original string
s=" hEllo world!\t " print("s.capitalize():",s.capitalize())#Title formatting print("s.center(20,'-'):",s.center(20,'-'))#Centers the string, fills the element with the specified number of characters print("s.count('l'):",s.count('l'))#Count occurrences of a string print("s.endswith:",s.endswith('d!'))#Determines whether the string is d!Ending print("s.find('o'):",s.find('o'))#Find the specified element,Find the index that returns it print("s.index('o'):",s.index('o'))#Find the specified element,Find the index that returns it sep='ABC' print("s.join(sep):",s.join(sep))#Put original character s Insert in the middle of every character (or element object) of the target print("s.lower():",s.lower())#Convert all to lowercase print("s.replace('l','j',1):",s.replace('l','j',1))#Replace the specified character, and the last is the number of replacements print("s.split():",s.split())#Cut string, cutting character as specified character print("s.strip():",s.strip())#Remove the left and right space elements, rstrip Only the right side is removed. lstrip Is to remove only the right side print("s.upper():",s.upper())#Full capitalization """is Series: isdigit()->Is it a number, isalnum()->Is it a letter or a number, isalpha()->Is it an English letter islower()->Is it all lowercase? """
Appeal Code Result:
s.capitalize(): hello world! s.center(20,'-'): -- hEllo world! --- s.count('l'): 3 s.endswith: False s.find('o'): 5 s.index('o'): 5 s.join(sep): A hEllo world! B hEllo world! C s.lower(): hello world! s.replace('l','j',1): hEjlo world! s.split(): ['hEllo', 'world!'] s.strip(): hEllo world! s.upper(): HELLO WORLD!
2. String formatting:
python string formatting --This seems to be all given by the parameter
>>> s="%d is 250" >>> s%250 '250 is 250' >>> b = "%(name)+10s----%(age)-10d----"%{'name':'xx','age':20} >>> print(b) xx----20 ---- >>> s="{:d} is a 250" >>> s.format(250) '250 is a 250' >>> a1 = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%},{:c}".format(15, 15, 15, 15, 15, 15.87623,65) >>> print(a1) numbers: 1111,17,15,f,F, 1587.623000%,A >>> s="{} {} 250" >>> s.format(250,"500-250") '250 500-250 250' >>> s.format(250,"500-250") '250 500-250 250'
3. Original string:
Cause: To avoid excessive use of \ to escape, when the string format is "string", all the characters inside are treated as characters, such as \n no longer wrapped.
>>> print("a\tb") a b >>> print(r"a\tb") a\tb
But the string cannot be processed if it ends with a \:
>>> print(r"c:\a\b") c:\a\b >>> print(r"c:\a\b\") SyntaxError: EOL while scanning string literal >>> print(r"c:\a\b\\") c:\a\b\\ >>> print(r"c:\a\b"+"\\") c:\a\b\
This is best handled using string splicing.
list
1. Common functions:
print("check".center(20,'-')) list_find=['apple','banana','pen',1,2,3] #Find subscripts for specified elements print(list_find.index('apple')) #Find the number of elements that exist print(list_find.count("apple")) print("increase".center(20,'-')) list_add=['apple','banana'] #Append element to end list_add.append("Hami melon") print(list_add) #Insert element to specified location list_add.insert(0,"Apple") print(list_add) print("Delete".center(20,'-')) list_del=[1,2,3,4,5,6,7,8,9] #Remove the element from the list (delete it), pop You can fill in parameters that are subscripts to deleted elements list_del.pop() print(list_del) #Delete the element with the specified element name list_del.remove(4) print(list_del) #Delete corresponding element space del list_del[0] print(list_del) print("Other".center(20,'-')) list_test4=['a','b','d','c'] list_test5=[1,2,3,4] #Extended List list_test5.extend(list_test4) print(list_test5) #Sort Lists list_test4.sort() print(list_test4)#Note: py3 Cannot sort elements of different types #Reverse List list_test5.reverse() print(list_test5)
The results of the above code run:
---------check---------- 0 1 ---------increase---------- ['apple', 'banana', 'Hami melon'] ['Apple', 'apple', 'banana', 'Hami melon'] ---------Delete---------- [1, 2, 3, 4, 5, 6, 7, 8] [1, 2, 3, 5, 6, 7, 8] [2, 3, 5, 6, 7, 8] ---------Other--------- [1, 2, 3, 4, 'a', 'b', 'd', 'c'] ['a', 'b', 'c', 'd'] ['c', 'd', 'b', 'a', 4, 3, 2, 1]
2. List Generation:
#exp = Expression # Process: 1.iteration iterable Each element in; # 2.Assign results to each iteration first iter_var,Then pass exp Get a new calculated value; #3. Final Pass All exp The resulting calculated value is returned as a new list. #[exp for iter_var in iterable] print("1.[exp for iter_var in iterable]") list1=[i for i in range(10)] print(list1) list2=[i*i for i in range(10,20)] print(list2) print("\n") #[exp for iter_var in iterable if_exp] print("2.[exp for iter_var in iterable if_exp]") list3=[i for i in range(10) if i%2==0] print(list3) print("\n") #[exp for iter_var_A in iterable_A for iter_var_B in iterable_B] print("3.[exp for iter_var_A in iterable_A for iter_var_B in iterable_B]") list4=[x*y for x in range(5) for y in range(5)] print(list4) print("\n")
The results of the above code run:
1.[exp for iter_var in iterable] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [100, 121, 144, 169, 196, 225, 256, 289, 324, 361] 2.[exp for iter_var in iterable if_exp] [0, 2, 4, 6, 8] 3.[exp for iter_var_A in iterable_A for iter_var_B in iterable_B] [0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 2, 4, 6, 8, 0, 3, 6, 9, 12, 0, 4, 8, 12, 16]
Dictionaries
1. Common functions:
d1={1:"Apple","Sprite":"Snow pear"} d1.clear()#Empty Dictionary print(d1) d1={1:"Apple","Sprite":"Snow pear"} print(d1.get(1))#Gets the result of the specified key in the dictionary print(d1.get(3))#If you get a key that does not exist, return None print(d1.items())#Get all key-value pairs of a dictionary print(d1.keys())#Get the key to the dictionary print(d1.values())#Get the value of the dictionary print(d1.pop(1))#Remove the specified subscript result print(d1.popitem())#Pop-up results without index print(d1) d1={1:"Apple","Sprite":"Snow pear"} d1.update({1:'apple',3:'pen'})#Update results, update same key names, and add results for new key names print(d1)
The results of the above code run:
{} //Apple None dict_items([(1, 'Apple'), ('Sprite', 'Snow pear')]) dict_keys([1, 'Sprite']) dict_values(['Apple', 'Snow pear']) //Apple ('Sprite', 'Snow pear') {} {1: 'apple', 'Sprite': 'Snow pear', 3: 'pen'}
aggregate
1. Common functions:
s1=set(['a','b','c']) print(s1.pop())#Randomly deletes an element from the set and returns its value print(s1) s3={'a','d'} s1.update(s3)#To update print(s1) s1.add('f')#Add Elements print(s1) s1.clear()#empty s1=set(['a','b','c','f']) print(s1) s1.remove('a')#Delete the target element, but error occurs if there are no elements in the collection print(s1) s1.discard('g')#If there are no elements in the collection, no error is reported; if there are elements, delete print(s1) b={'a','b','g'} print("s1.difference(b)") print(s1.difference(b))# Take Set s Yes, b And returns the set of elements print("s1.interscetion(b)") print(s1.intersection(b))#Intersection, two s and b Intersection in, return s,b A collection of elements that exist in all print("s1.issubset(b)") print(s1.issubset(b))#judge s Is it b A subset of print("s1.issuperset(b)") print(s1.issuperset(b)) #judge s Is it b The parent set of print("s1.symmetric_difference(b)") print(s1.symmetric_difference(b)) #Take the difference set and create a new set print("s1.union(b)") print(s1.union(b)) #Union print("symmetric_difference_update") print(s1) s1.symmetric_difference_update(b)#No return value print(s1) """ xxxx_update Meeting Coverage s1 A value of, for example: s1.symmetric_difference_update() //The value of s1 is overridden when the result of symmetric_difference is obtained """
The above code results:
a {'c', 'b'} {'c', 'b', 'd', 'a'} {'c', 'b', 'd', 'f', 'a'} {'a', 'c', 'b', 'f'} {'c', 'b', 'f'} {'c', 'b', 'f'} s1.difference(b) {'c', 'f'} s1.interscetion(b) {'b'} s1.issubset(b) False s1.issuperset(b) False s1.symmetric_difference(b) {'a', 'g', 'c', 'f'} s1.union(b) {'g', 'c', 'b', 'f', 'a'} symmetric_difference_update {'c', 'b', 'f'} None {'g', 'c', 'f', 'a'}