Related links
Variable sequence : The execution sequence can be incremented 、 Delete 、 Change operation , The object address does not change .
① list list -> [v1,v2,…]、② aggregate set -> {k1,k2,…}、③ Dictionaries dict -> {k1:v1,…}
Immutable sequence : No increase 、 Delete 、 Change the operation . Because of its immutable nature , In a multithreaded scenario , No need to lock .
① Tuples tuple -> (v1,v2,…) 、② character string str -> ‘’
""" @author GroupiesM @date 2022/6/22 16:11 @introduction Variable sequence : list list、 Dictionaries dict、 aggregate set The execution sequence can be incremented 、 Delete 、 Change operation , The object address does not change Immutable sequence : Tuples tuple、 character string str No increase 、 Delete 、 Change the operation """
''' Variable sequence list list、 Dictionaries dict、 aggregate set'''
lst = [10, 20, 45]
lst.append(300)
print(lst) # [10, 20, 45, 300]
''' Immutable sequence Tuples tuple、 character string str'''
t = ('python', 5)
print(t) # ('python', 5)
""" @author GroupiesM @date 2022/4/29 09:25 @introduction Immutable sequence ( Tuples 、 character string ) In the scenario of multiple threads , There is no need to lock when operating the same object at the same time matters needing attention : Tuples store references to objects a) If the object itself in the tuple is immutable , That is, the memory address pointed to is immutable b) If the object in the tuple is a non basic type , You can modify the data """
t = (10, [20, 30], 9)
print(t) # (10, [20, 30], 9)
''' When the element in a tuple is a reference type , You can modify the data of the reference type '''
t[1].remove(30) # (10, [20], 9)
print(t) # (10, [20], 9)
''' The memory address of the element cannot be modified '''
t[1] = [50]
print(t) # TypeError: 'tuple' object does not support item assignment
P.S:
1. Immutable sequences do not change in memory
2. If you make a change to an immutable sequence , The sequence will be stored in the new address space , And the original sequence because of the garbage collection mechanism , Will be recycled .
3. When the variable sequence changes , Will not change the address , Instead, change the value in memory , Or expand memory space .
4. Dictionaries Is a variable sequence , But the keys of the dictionary are immutable , And the value is variable . Because the principle of dictionary structure is the hash table of pseudo-random detection , It looks up by passing a key through a hash function , Find the memory address of the value . Therefore, the hash value is generally unique or the conflict is relatively small . If you change the value of the key ,name The hash value will change , The original value cannot be found , So the value of the key is immutable . After the key hash, it points to the address in memory , Changes in the data in memory do not affect the search of the dictionary .
""" @author GroupiesM @date 2022/4/28 17:13 @introduction <class 'tuple'> list :list = ['hello', 'world', 100] Dictionaries :dict = {'name': ' Zhang San ', 'age': 100} Tuples :tuple = ('python','hello',90) aggregate : set = {'python', 'hello', 90} character string : str = 'python' """
t = ('python', 'hello', 90)
print(type(t)) # <class 'tuple'>
print(t) # ('python', 'hello', 90)
""" @author GroupiesM @date 2022/4/28 17:55 @introduction Tuple creation method : Mode one : Use parentheses (), Elements are separated by English commas ; Add a comma when there is only one element , Otherwise, the data type is the basic data type tup = ('python',) tup = (1,3,5) Mode two : Built in functions tuple() Type conversion tuple(('hello','php')) # list -> tuple tuple({'name': ' Zhang San ', 'age': 100}) # Dictionaries -> tuple tuple(['hello','php']) # Tuples -> tuple tuple({'python', 'hello', 90}) # aggregate -> tuple tuple('hello') # character string ->tuple """
''' Mode one '''
lst = ['hello', 'python']
print(lst) # ['hello', 'python']
''' Mode two '''
'''1.list->tuple'''
lst1 = tuple(('hello', 'php')) # list -> tuple
print('lst1', lst1) # ('hello', 'php')
'''2. Dictionaries ->tuple when , Take the dictionary automatically key'''
lst2 = tuple({
'name': ' Zhang San ', 'age': 100}) # Dictionaries -> tuple
print('lst2', lst2) # ('name', 'age')
'''3. Tuples ->tuple'''
lst3 = tuple(['hello', 'php']) # Tuples -> tuple
print('lst3', lst3) # ('hello', 'php')
'''4. aggregate ->tuple'''
lst4 = tuple({
'python', 'hello', 90}) # aggregate -> tuple
print('lst4', lst4) # ('python', 'hello', 90)
'''5. character string ->tuple'''
lst5 = tuple('hello') # character string ->tuple
print('lst5', lst5) # ('h', 'e', 'l', 'l', 'o')
""" @author GroupiesM @date 2022/4/29 15:04 @introduction Use for-in Traverse : Tuples are iteratable objects t = ('Python','hello',90) for i in t: print(i) """
t = ('Python', 'hello', 90)
for i in t:
print(i, end="\t") # Python hello 90
print()
for i in range(0, len(t)):
print(t[i], end="\t") # Python hello 90
""" @author GroupiesM @date 2022/6/27 16:57 @introduction """
1. How to query
index(): Find substring substr First occurrence , If the substring you are looking for does not exist , Throw out ValueError
rindex(): Find substring substr The last location , If the substring you are looking for does not exist , Throw out ValueError
find(): Find substring substr First occurrence , If the substring you are looking for does not exist , Then return to -1
rfind(): Find substring substr The last location , If the substring you are looking for does not exist , Then return to -1
2. toggle case
upper(): Converts all characters in a string to uppercase letters
lower(): Converts all characters in a string to lowercase letters
swapcase(): Convert all uppercase letters in the string to lowercase letters , Turn all lowercase letters into uppercase letters
capitalsize(): The entire string is capitalized , The rest of the letters are lowercase
title(): Capitalize the first letter of each word , The rest of the letters are lowercase
3. Content alignment
center(): Align center , The first 1 Two parameters specify the width , The first 2 A parameter specifies the filler , The first 2 Two parameters are optional , Default is space , If the set width is less than the actual width, the original string is returned
ljust(): Align left , The first 1 Two parameters specify the width , The first 2 A parameter specifies the filler , The first 2 Two parameters are optional , Default is space , If the set width is less than the actual width, the original string is returned
rjust(): Right alignment , The first 1 Two parameters specify the width , The first 2 A parameter specifies the filler , The first 2 Two parameters are optional , Default is space , If the set width is less than the actual width, the original string is returned
zfill(): Right alignment , Use... On the left 0 fill , The first 1 Two parameters specify the width , If the set width is less than the actual width, the original string is returned
4. Segmentation of strings
split(self,sep,maxsplit): Split from the left of the string , Return a list
self: The string itself
sep: Specify the separator , Default is space
maxsplit: Specify the maximum number of divisions , After the specified number of divisions , The remaining strings as a whole are no longer split
rsplit(): Start with the right side of the string , Return a list ( Parameters are the same )
5. String judgment
isidentifier(): Legal variable name ( The variable name that can be used as the receiving variable )
isspace(): All consist of empty strings ( enter 、 Line break 、 Horizontal tabs )
isalpha(): All by letters
isdecimal(): It's all made up of decimal numbers
isnumeric(): It's all made up of numbers ( Chinese simplified 、 traditional Chinese character , Symbol , Rome digital )
isalnum(): It consists entirely of letters and numbers
6. String substitution
replace(old,new):
replace(old,new,count):
self: The default string itself
1.old: String before replacement
2.new: Replaced string
3.count: Maximum number of replacements ,( Parameters can be omitted )
7. String merge
join(): Combine strings from a list or tuple into one string , The elements of a list or tuple must all be strings
8. String comparison
Operator :>,>=,<,<=,==,!=
Compare the rules : First compare the first character in two strings , If equal, continue to compare the next character ,
Compare it in turn , Until the characters in the two strings are not equal , The comparison result is the result of two strings
Comparison results , All subsequent characters in the two strings will no longer be compared
Comparison principle :
Compare two characters , The comparison is its ASCII Code value
With built-in functions ord( character ), You can get the corresponding characters ASCII Code value ( Numbers )
With built-in functions chr( Numbers ), You can get the number corresponding to character
9. character formatting
%-formatting、format、f-String
10. String encoding and decoding
encode(String encoding): code , Convert string to binary data (bytes)
decode(String encoding): decode , take bytes Convert data of type to string type
""" @author GroupiesM @date 2022/5/9 14:03 @introduction <class 'str'> list :list = ['hello', 'world', 100] Dictionaries :dict = {'name': ' Zhang San ', 'age': 100} Tuples :tuple = ('python','hello',90) aggregate : set = {'python', 'hello', 90} character string : str = 'python' """
''' String definition : There are three ways , Single quotation marks 、 Double quotes 、 Three quotes '''
str1 = 'python'
str2 = "python"
str3 = ''''python'''
print(type(str1)) # <class 'tuple'>
print(str1) # ('python', 'hello', 90)
""" @author GroupiesM @date 2022/5/9 14:14 @introduction One 、 Resident mechanism 1)python The string in is the basic type , It's an immutable sequence of characters 2) What is the string persistence mechanism 【 The memory address of the same string is also equal 】 The method of saving only one copy of the same and immutable string , Different values are stored in the resident pool of strings , Python Only one copy of the same string is retained by the resident mechanism of , When the same string is created later , There will be no new space , Instead, assign the address of the string to the new variable Two 、 matters needing attention 1、 Dwell condition of string Just letters 、 Numbers 、 String of underscores ,python Will enable the resident mechanism , because Python The interpreter is only for those that look like python The identifier string uses intern() Method , and python The identifier is made up of letters 、 Numbers and underscores . 2、 String connection String data type , It's an immutable type , We all know , If we have a string , Want to modify it , no , You must create a new object , Therefore, it is not recommended “+” Connection string , We recommend that you use join() Method 3、 Integer resident python The integer range is [-5, 256] Integer enable dwell mechanism for (python These figures are commonly used , Put it in the cache to save expenses ) 4、 stay pycharm And black windows (iterm) The test results are different , The specific reason is unknown 1)teminal: Do not trigger the string persistence mechanism 2)pycharm: Trigger string resident mechanism P.S Comparison operator : == -> value Comparison is,is not Memory address comparison """
str1 = "abc"
str2 = "abc" # The memory address of the same string is also equal -> str1 And str2 Memory addresses are equal
str3 = "".join(['ab', 'c'])
print(str1, type(str1), id(str1)) # abc <class 'str'> 4378617712
print(str2, type(str2), id(str2)) # abc <class 'str'> 4378617712
# Conclusion : str1、str2 The address of is equal to
print(str3, type(str3), id(str3)) # abc <class 'str'> 4381017264
""" Testing in different scenarios involves [\w\d_] Characters other than ,python String resident mechanism (python3.8.9) 1)terminal: Do not trigger the string persistence mechanism 2)pycharm: Trigger string resident mechanism """
"""1) terminal: [email protected] ~ % python3 Python 3.8.9 (default, Feb 18 2022, 07:45:33) [Clang 13.1.6 (clang-1316.0.21.2)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> str4='abc%' >>> str5='abc%' >>> str4==str5 True >>> str4 is str5 False >>> """
"""2) pycharm:"""
str4 = 'abc%'
str5 = 'abc%'
print(str4 == str5) # True Compare value
print(id(str4)) # 4300391152
print(id(str5)) # 4300391152
print(str4 is str5) # True Compare memory addresses
""" @author GroupiesM @date 2022/5/23 17:01 @introduction Query methods : index(): Find substring substr First occurrence , If the substring you are looking for does not exist , Throw out ValueError rindex(): Find substring substr The last location , If the substring you are looking for does not exist , Throw out ValueError find(): Find substring substr First occurrence , If the substring you are looking for does not exist , Then return to -1 rfind(): Find substring substr The last location , If the substring you are looking for does not exist , Then return to -1 """
s = 'hello,hello'
print(s.index('lo')) # 3
print(s.rindex('lo')) # 9
print(s.find('lo')) # 3
print(s.rfind('lo')) # 9
# print(s.index('k')) # Report errors If the substring you are looking for does not exist , Throw out ValueError
# print(s.rindex('k')) # Report errors If the substring you are looking for does not exist , Throw out ValueError
print(s.find('k')) # -1
print(s.rfind('k')) # -1
""" @author GroupiesM @date 2022/6/20 09:34 @introduction toggle case : upper(): Converts all characters in a string to uppercase letters lower(): Converts all characters in a string to lowercase letters swapcase(): Convert all uppercase letters in the string to lowercase letters , Turn all lowercase letters into uppercase letters capitalsize(): The entire string is capitalized , The rest of the letters are lowercase title(): Capitalize the first letter of each word , The rest of the letters are lowercase """
s = 'hEllo WoRld'
print(s, id(s)) # hEllo WoRld 4333433968
print(s.upper(), id(s.upper())) # HELLO WORLD 4333137520
print(s.lower(), id(s.lower())) # hello world 4333137520
print(s.swapcase(), id(s.swapcase())) # HeLLO wOrLD 4333137520
print(s.capitalize(), id(s.capitalize())) # Hello world 4333137520
print(s.title(), id(s.title())) # Hello World 4333137520
""" @author GroupiesM @date 2022/6/20 10:33 @introduction Content alignment : center(): Align center , The first 1 Two parameters specify the width , The first 2 A parameter specifies the filler , The first 2 Two parameters are optional , Default is space , If the set width is less than the actual width, the original string is returned ljust(): Align left , The first 1 Two parameters specify the width , The first 2 A parameter specifies the filler , The first 2 Two parameters are optional , Default is space , If the set width is less than the actual width, the original string is returned rjust(): Right alignment , The first 1 Two parameters specify the width , The first 2 A parameter specifies the filler , The first 2 Two parameters are optional , Default is space , If the set width is less than the actual width, the original string is returned zfill(): Right alignment , Use... On the left 0 fill , The first 1 Two parameters specify the width , If the set width is less than the actual width, the original string is returned """
s = 'hello world'
''' Specify fill '''
print(s.center(20, '*')) # ****hello world*****
print(s.ljust(20, '&')) # hello world&&&&&&&&&
print(s.rjust(20, '^')) # ^^^^^^^^^hello world
print(s.zfill(20)) # 000000000hello world
''' Do not specify fill '''
print(s.center(20)) # hello world
print(s.ljust(20)) #hello world
print(s.rjust(20)) # hello world
print(s.zfill(20)) # 000000000hello world
''' Specify the width < String length '''
print(s.center(5)) # hello world
print(s.ljust(4)) # hello world
print(s.rjust(3)) # hello world
print(s.zfill(2)) # hello world
""" @author GroupiesM @date 2022/6/20 10:44 @introduction split()- Division : split(self,sep,maxsplit): Split from the left of the string , Return a list self: The string itself sep: Specify the separator , Default is space maxsplit: Specify the maximum number of divisions , After the specified number of divisions , The remaining strings as a whole are no longer split rsplit(): Start with the right side of the string , Return a list ( Parameters are the same ) """
s = 'a1b1c d1e1f g h'
print(s.split()) # ['a1b1c', 'd1e1f', 'g', 'h']
print(s.split(sep='1')) # ['a', 'b', 'c d', 'e1f']
print(s.split(maxsplit=3)) # ['a', 'b', 'c d', 'e', 'f g h']
print(s.split(sep='1', maxsplit=3)) # ['a', 'b', 'c d', 'e1f g h']
print('----')
print(s.rsplit()) # ['a1b1c', 'd1e1f', 'g', 'h']
print(s.rsplit(sep='1')) # ['a', 'b', 'c d', 'e', 'f g h']
print(s.rsplit(maxsplit=3)) # ['a1b1c', 'd1e1f', 'g', 'h']
print(s.rsplit(sep='1', maxsplit=3)) # ['a1b', 'c d', 'e', 'f g h']
""" @author GroupiesM @date 2022/6/20 11:21 @introduction Judge : isidentifier(): Legal variable name ( The variable name that can be used as the receiving variable ) isspace(): All consist of empty strings ( enter 、 Line break 、 Horizontal tabs ) isalpha(): All by letters isdecimal(): It's all made up of decimal numbers isnumeric(): It's all made up of numbers ( Chinese simplified 、 traditional Chinese character , Symbol , Rome digital ) isalnum(): It consists entirely of letters and numbers """
print('---isidentifier() Legal variable name ( The variable name that can be used as the receiving variable )---')
print('if'.isidentifier()) # True
print('_b'.isidentifier()) # True
print(' Zhang San '.isidentifier()) # True
print('8a'.isidentifier()) # False
print(''.isidentifier()) # False
print('---isspace() All consist of empty strings ( enter 、 Line break 、 Horizontal tabs )---')
print(' \r\t\n'.isspace()) # True
print(' \r\t\n0'.isspace()) # False
print('---isalpha() All by letters ---')
print('abc'.isalpha()) # True
print(' Zhang San '.isalpha()) # True
print(' Zhang San 1'.isalpha()) # False
print('---isdecimal(): It's all made up of decimal numbers ---')
print('123'.isdecimal()) # True
print('12 3、 ... and '.isdecimal()) # True
print('123.4'.isdecimal()) # False
print('123 '.isdecimal()) # False
print('---isnumeric(): It's all made up of numbers ( Chinese simplified 、 traditional Chinese character , Symbol , Rome digital )---')
print('12'.isnumeric()) # True
print('12② Ii. Ⅱ'.isnumeric()) # True
print('1two'.isnumeric()) # False
print('---isalnum(): It consists entirely of letters and numbers ---')
print(' Zhang San 8'.isalnum()) # True
print(' Zhang San 8 '.isalnum()) # False
""" @author GroupiesM @date 2022/6/20 12:04 @introduction Replace : replace(String old,String new): replace(String old,String new,Integer count): self: The default string itself 1.old: String before replacement 2.new: Replaced string 3.count: Maximum number of replacements ,( Parameters can be omitted ) """
s = '12 12 12'
print(s.replace(' ', '\r\n', 1))
''' 12 12 12 '''
print('---')
print(s.replace(' ', '\r\n'))
''' 12 12 12 '''
""" @author GroupiesM @date 2022/6/20 12:12 @introduction Merge : join(): Combine strings from a list or tuple into one string , The elements of a list or tuple must all be strings """
lst =['1 ','2 ','345']
print(''.join(lst)) # 1 2 345
lst =['1 ','2 ',345]
print(''.join(lst)) # TypeError: sequence item 2: expected str instance, int found
""" @author GroupiesM @date 2022/6/21 16:57 @introduction Compare : Operator :>,>=,<,<=,==,!= Compare the rules : First compare the first character in two strings , If equal, continue to compare the next character , Compare it in turn , Until the characters in the two strings are not equal , The comparison result is the result of two strings Comparison results , All subsequent characters in the two strings will no longer be compared Comparison principle : Compare two characters , The comparison is its ASCII Code value With built-in functions ord( character ), You can get the corresponding characters ASCII Code value ( Numbers ) With built-in functions chr( Numbers ), You can get the number corresponding to character """
'''>'''
print("apple" > "app") # True
print('a' > ' Zhang ') # False
print(ord('a')) # 97
print(ord(' Zhang ')) # 24352
print(chr(97)) # a
''' == And is The difference between == The comparison is value is The comparison is id Whether it is equal or not ( Memory address ) '''
a = 'ab'
b = "".join(['a', 'b'])
'''a And b Of value 、 Memory address '''
print(a, id(a)) # ab 4375883376
print(b, id(b)) # ab 4377252400
print(a == b) # True :a And b The values are equal
print(a is b) # False :a And b Memory addresses are not equal
""" @author GroupiesM @date 2022/6/22 11:28 @introduction section : 1. Strings are immutable types , No increase 、 Delete 、 Change the operation 2. Strings are immutable types , The slicing operation will produce new objects Assuming a string str = 'hello,python', It is known that str The length is 11 0 1 2 3 4 5 6 7 8 9 10 11 [ Forward index ] h e l l o , p y t h o n -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 [ Reverse index ] Understanding can Slice Syntax 1:newStr = str[ start (x): end (y): step (s)] among x,y For any integer , Indicates the index position among s For any integer , Indicating step size ( Several positions are separated from each character ) 1. start (x) You can omit it , If it is not written, the default value will be taken 0; for example str[:5] <=> str[0:5] 2. end (y) You can omit it , If it is not written, the default value will be taken End of string ; for example str[6:] <=> str[6:11] 3. step (s) You can omit it , If it is not written, the default value will be taken 1; for example str[:5:] <=> str[:5:1] 4. if start (x)> end (y), The generated new string is an empty string '' 5. if 0 < start (x) < end (y), According to Forward index Slice 6. if start (x) < end (y) < 0, According to Reverse index Slice . There are basically no usage scenarios , Understanding can 7. if s<0, Then the string is inversely sliced """
str = 'hello,python'
s1 = str[:5] # str[:5] <=> str[0:5] The two expressions are equivalent
print('s1', s1) # hello
s2 = str[6:] # str[6:] <=> str[6:11] The two expressions are equivalent
print('s2', s2) # python
s3 = str[:] # str[:] <=> str[0:11] The two expressions are equivalent
print('s3', s3) # hello,python
s4 = str[0:5:] # str[0:5:] <=> str[0:5:1] The two expressions are equivalent
print('s4', s4) # hello
s5 = str[-5:-1]
print('s5', s5) # s5 ytho
s6 = str[0:5:1]
print('s6', s6) # hlo
s7 = str[-15:-1] # s<0, Reverse slice
print('s7', s7) # nohtyp,olleh
""" @author GroupiesM @date 2022/6/27 16:48 @introduction String encoding and decoding : Purpose : Used for data transmission in the network (byte Byte transmission ) encode(String encoding): code , Convert string to binary data (bytes) decode(String encoding): decode , take bytes Convert data of type to string type P.S 1. Encoding mode : Common coding methods are GBK、UTF-8 2. The most common cause of garbled code is inconsistent encoding and decoding """
s = ' take bytes Convert data of type to string type '
# code - b'\xbd\xabbytes\xc0\xe0\xd0\xcd\xb5\xc4\xca\xfd\xbe\xdd\xd7\xaa\xbb\xbb\xce\xaa\xd7\xd6\xb7\xfb\xb4\xae\xc0\xe0\xd0\xcd'
g_encode = s.encode('GBK')
g_encode = s.encode(encoding='GBK')
print(g_encode)
# decode - take bytes Convert data of type to string type
g_decode = g_encode.decode('GBK')
g_decode = g_encode.decode(encoding='GBK')
print(g_decode)
22/06/28
M