Details today
Data Type Built in Method Theory
Each data type we have learned before contains a series of operation methods,Built in methods are the most(Built in functions) stay python The uniform sentence pattern of calling built-in methods for data types in is>>>:Period 'jason'.String built-in method Variable name of binding string.String built-in method str.String built-in method ps:There are many built-in methods for data types. If we want to master them, we should not just rely on rote memorization. More often, practice makes perfect
Integer built-in methods and operations
1. Type conversion
int(Other data types) ps: Floating point type can be directly converted to string only if it is a pure number a = int(11.11) # 11 a = int(11.57) # 11 a = int('11') # 11 a = int('11.11') # The string must be a pure number before it can be converted, otherwise an error is reported
2. Conversion of decimal number
Decimal to other decimal print(bin(23)) # 0b10111 print(oct(23)) # 0o27 print(hex(23)) # 0x17 ''' If the beginning of the number is 0 b Then binary 0 o Octal 0 x Hexadecimal ''' Other decimal to decimal print(int(0b10111)) # 23 print(int(0o27)) # 23 print(int(0x17)) # 23 String base number to decimal print(int("0b1100100", 2)) # 100 print(int("0o144", 8)) # 100 print(int("0x64", 16)) # 100
3.python itself is less sensitive to numbers (low accuracy)
python This language is really not powerful at all, mainly because there are too many big guys behind it If the calculation needs to be calibrated, the module numpy..... s1 = 1.1 s2 = 1 print(s1 - s2)
Floating point built-in methods and operations
1. Type conversion
float(Other data types) A decimal point can be allowed in the string, and the rest must be pure numbers res = float(11) # 11.0 <class 'float'> res = float('11') # 11.0 <class 'float'> res = float('11.11') # 11.11 <class 'float'> res = float('1.1.1.1') # ValueError: could not convert string to float: '1.1.1.1' res = float('abc') # could not convert string to float: 'abc' print(res, type(res))
2.python itself is less sensitive to numbers (low accuracy)
python This language is really not powerful at all, mainly because there are too many big guys behind it If the calculation needs to be calibrated, the module numpy.....
String built-in methods and operations
1. Type conversion
str(Other data types) ps:Can be converted to any data type(Just put quotation marks around)
2. Common methods
2.1 Index value (error is reported directly when the starting position 0 exceeds the range)
s1 = 'helloworld' print(s1[0]) # h print(s1[-1]) # d Support negative numbers starting from the end
2.2 Slicing operation
print(s1[1:5]) # Gu Tou cuts from index 1 to index 4 regardless of the tail print(s1[-1:-5]) # The default order is from left to right. Although no error is reported, the desired result will not be printed print(s1[-5:-1]) # The default order is from the fifth to the last word from left to right
2.3 Modify slice direction (spacing)
print(s1[1:5:1]) # The default step size is 1. Start from index 1 step by step until index 4. Run ello print(s1[1:5:2]) # Change the step size to 2 from index 1 to index 4. Run el with a step size difference of 2 for each index value print(s1[-1:-5:-1]) # Changed the order to run dlro from the end index - 1 to the index - 4 print(s1[:]) # Run helloworld by default without writing numbers print(s1[2:]) # Run lloworld from index 2 onwards print(s1[:5]) # Run hello from index 0 to 4 print(s1[::2]) # All, but run hlool in steps of 2
2.4 Count the number of characters in a string
len() returns the length of string, list, dictionary, tuple, etc.
print(len(s1)) # 10
2.5 Remove the characters specified at the beginning and end of the string
The strip() method is used to remove the characters specified at the beginning and end of the string
Do not write in parentheses. Remove the leading and trailing spaces by default
username = input('username>>>:').strip() # username = username.strip() # This step can be omitted. You can remove the leading and trailing space symbols when entering the user name if username == 'jason': print('Login succeeded') res = ' jason ' # There are two space characters at the beginning and the end respectively 9 print(len(res)) # Number of characters 9 print(len(res.strip())) # The number of characters after removing the leading and trailing spaces is 5 res1 = '$$jason$$' print(res1.strip('$')) # jason removes the first and last $characters print(res1.lstrip('$')) # Jason $$lstrip removes the left $character print(res1.rstrip('$')) # $$jason rstrip removes the right $character
2.6 Cutting characters specified in a string
split() can split any string and text according to the specified rules (text, symbol, etc.) and return a list value.
res = 'jason|123|read' print(res.split('|')) # ['jason ',' 123 ',' read '] The processing result of this method is a list name, pwd, hobby = res.split('|') print(res.split('|', maxsplit=1)) # ['jason ',' 123 | read '] Specify the number from left to right print(res.rsplit('|', maxsplit=1)) # ['jason | 123 ',' read '] Specify the number from right to left
2.7 String format output
format() format output replaces the traditional% with {} to achieve formatted output
format Play 1:Equivalent to Placeholder res = 'my name is {} my age is {}'.format('jason', 123) print(res) # my name is jason my age is 123 format Play 2:Index value and support repeated use res = 'my name is {0} my age is {1} {0} {0} {1}'.format('jason', 123) print(res) # my name is jason my age is 123 jason jason 123 format Play 3:Placeholder refers to name and meaning res = 'my name is {name1} my age is {age1} {name1} {age1} {name1} '.format(name1='jason', age1=123) # It is different from index values in the same way print(res) format Play 4:Recommended(******) It is recommended not to define values in advance, but to customize values as the case may be name = input('username>>>:') age = input('age>>>:') res = f'my name is {name} my age is {age}' print(res)
3. Methods to be understood
3.1 Case dependency
upper() acts on the conversion of lower case letters into upper case letters in the string.
lower() converts all uppercase letters in the string to lowercase letters
res = 'hElLO WorlD 666' print(res.upper()) # HELLO WORLD 666 Convert all strings to uppercase print(res.lower()) # hello world 666 Convert all to lowercase '''Picture verification code:Generate a verification code without uniform case and show it to the user Obtain the verification code entered by the user, convert the verification code entered by the user and the original verification code to uppercase or lowercase, and then compare them ''' code = '8Ja6Cc' print('Picture verification code displayed to users', code) confirm_code = input('Please enter the verification code').strip() if confirm_code.upper() == code.upper(): # Convert the input verification code and the original verification code into upper case or lower case for comparison print('The verification code is correct') else: print('Verification code error') res = 'hello world' print(res.isupper()) # Judge whether the string is pure uppercase False print(res.islower()) # Judge whether the string is pure lowercase True
3.2 Judge whether the string is a pure number
The isdigit() method detects whether a string consists of only numbers and is valid only for 0 and positive numbers.
Returns True if the string contains only numbers, otherwise returns False
res = '0' print(res.isdigit()) # True guess_age = input('guess_age>>>:').strip() # Enter the age and remove the spaces mistyped at the beginning and end if guess_age.isdigit(): # Judge whether the entered age is a pure number guess_age = int(guess_age) # Convert the input value to an integer if conditions are met else: print('Don't you know how to lose even when you are old???')
3.3 Replace the content specified in the string
Replace() is to replace old (old string) in the string with new (new string). If the third parameter max is specified, the replacement will not exceed max times.
res = 'my name is qyf qyf qyf qyf qyf qyf' print(res.replace('qyf', '666')) # my name is 666 666 666 666 666 666 print(res.replace('qyf', '333', 3)) # my name is 333 333 333 qyf qyf qyf replace the specified number of contents from left to right replace the specified number of contents from left to right
3.4 String splicing
The join() method is used to connect the elements in the sequence with the specified characters to generate a new string
ss1 = 'hello' ss2 = 'world' print(ss1 + '$$$' + ss2) # hello$$$world print(ss1 * 10) # hellohellohellohellohellohellohellohellohellohello print('|'.join(['jason', '123', 'read', 'JDB'])) # jason|123|read|JDB print('|'.join(['jason', 123])) # The data values involved in splicing must all be strings, otherwise an error will be reported!!!
3.5 Count the number of occurrences of specified characters
count() counts the number of occurrences of a character in a string/list/tuple. You can set the start position or end position.
res = 'hello world lalla' print(res.count('l')) # 6 print(res.count('l', 4)) # 4 print(res.count('l', 5, 13)) # 2
3.6 Judge the beginning or end of a string
startswith() determines whether the string starts with the specified character or substring
endswith() is used to determine whether a string in a string ends with a specified character or substring
res = 'jason say hello' print(res.startswith('jason')) # True print(res.startswith('j')) # True print(res.startswith('jas')) # True print(res.startswith('a')) # False print(res.startswith('son')) # False print(res.startswith('say')) # False print(res.endswith('o')) # True print(res.endswith('llo')) # True print(res.endswith('hello')) # True
3.7 Other methods supplement
title() returns the 'captioned' string, that is, the beginning of the word is uppercase, and the rest is lowercase
Capitalization () returns a string in uppercase, where the first character of the sentence is uppercase and the rest are lowercase
swapcase() is used to convert uppercase and lowercase letters of a string
index() is used to find the index position of the first match of a value from the list. If no object is found, an exception is thrown
The find() function is used to retrieve strings and output operation values. If not, it returns - 1 directly
res = 'helLO wORld hELlo worLD' print(res.title()) # Hello World Hello World print(res.capitalize()) # Hello world hello world print(res.swapcase()) # HELlo WorLD HelLO WORld print(res.index('O')) # 4 print(res.find('O')) # 4 print(res.index('c')) # No direct error is found print(res.find('c')) # Default return - 1 not found print(res.find('LO')) # 3
List built-in methods and operations
1. Type conversion
list(Other data types) ps:Can be for Circular data types can be converted into lists print(list('hello')) print(list({'name': 'jason', 'pwd': 123})) print(list((1, 2, 3, 4))) print(list({1, 2, 3, 4, 5}))
2. Methods to be mastered
2.1 Index value (positive and negative number)
11 = [111, 222, 333, 444, 555, 666, 777, 888] print(l1[0]) # 111 print(l1[-1]) # 888
2.2 The slicing operation is consistent with the string interpretation operation
print(l1[0:5]) # [111, 222, 333, 444, 555] print(l1[:]) # [111, 222, 333, 444, 555, 666, 777, 888] All
2.3 Interval number direction is consistent with string interpretation
print(l1[::-1]) # [888, 777, 666, 555, 444, 333, 222, 111] Change direction and all
2.4 Number of data values in statistical list
print(len(l1)) # 8
2.5 Data value modification
l1[0] = 123 print(l1) # [123, 222, 333, 444, 555, 666, 777, 888]
2.6 Adding Data Values to a List
Mode 1:Append data value at the end l1.append('Dry rice') print(l1) # [111, 222, 333, 444, 555, 666, 777, 888, 'dry rice'] l1.append(['jason', 'kevin', 'jerry']) print(l1) # [111, 222, 333, 444, 555, 666, 777, 888, ['jason', 'kevin', 'jerry']] Mode 2:Insert data values anywhere insert()The given element can be inserted into the given index in the list l1.insert(0, 'jason') print(l1) # ['jason', 111, 222, 333, 444, 555, 666, 777, 888] l1.insert(1, [11, 22, 33, 44]) print(l1) # [111, [11, 22, 33, 44], 222, 333, 444, 555, 666, 777, 888] Mode 3:Expand List Merge List ll1 = [11, 22, 33] ll2 = [44, 55, 66] print(ll1 + ll2) # [11, 22, 33, 44, 55, 66] extend()Function is mainly used to append multiple values in another sequence at the end of the list(Expand the original list with the new list). ll1.extend(ll2) # for loop+append print(ll1) # [11, 22, 33, 44, 55, 66] for i in ll2: ll1.append(i) print(ll1) # [11, 22, 33, 44, 55, 66]
2.7 Deleting List Data
Mode 1:General deletion keywords del Delete according to the index; Delete elements within the index range; Delete the entire list. del l1[0] print(l1) # [222, 333, 444, 555, 666, 777, 888] Mode 2:remove Search and delete according to elements; Delete the first corresponding element; Confirm that there is an element in the list, and delete it l1.remove(444) # Fill in data value in parentheses print(l1) # [111, 222, 333, 555, 666, 777, 888] Mode 3:pop()Remove the element at the specified position in the list, and assign the removed element to a variable l1.pop(3) # Fill in the index value in brackets print(l1) # [111, 222, 333, 555, 666, 777, 888] l1.pop() # Default tail pop-up data value print(l1) # [111, 222, 333, 444, 555, 666, 777] res = l1.pop(3) print(res) # 444 res1 = l1.remove(444) print(res1) # None
2.8 Sorting
ss = [54, 99, 55, 76, 12, 43, 76, 88, 99, 100, 33] ss.sort() # The default is ascending print(ss) # [12, 33, 43, 54, 55, 76, 76, 88, 99, 99, 100] ss.sort(reverse=True) # Change to descending order print(ss) # [100, 99, 99, 88, 76, 76, 55, 54, 43, 33, 12]
2.9 Count the number of occurrences of a data value in the list
print(l1.count(111)) # 1
2.10 Reversing the list order
l1.reverse() # Reverse is a built-in function of a list in python. It is unique to the list and is used to reverse the data in the list print(l1) # [888, 777, 666, 555, 444, 333, 222, 111]
Variable and immutable types
s1 = '$$jason$$' l1 = [11, 22, 33] s1.strip('$') print(s1) # $$jason$$ res = s1.strip('$') print(res) # jason ''' After calling the built-in method, the string will not modify itself but produce a new result How to check whether there are new results after calling the method. You can add variable names and assignment symbols on the left side of the code calling the method ''' ret = l1.append(44) print(l1) # [11, 22, 33, 44] print(ret) # None '''The list is modified after calling the built-in method, but it does not produce a new result''' Variable type:Value changes, memory address remains unchanged # l1 = [11, 22, 33] # print(l1) # print(id(l1)) # 2180443267776 # l1.append(44) # print(l1) # print(id(l1)) # 2180443267776 Immutable type:Value change Memory address must change res = '$$hello world$$' print(res) # $$hello world$$ print(id(res)) # 2177293876720 res1 = res.strip('$') print(res) # hello world print(id(res)) # 2177298789552