Python Study Notes 3-strings, python Study Notes 3-
Format String/compound field name
>>> import humansize>>> si_suffixes = humansize.SUFFIXES[1000]>>> si_suffixes['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']>>> '1000{0[0]} = 1{0[1]}'.format(si_suffixes)'1000KB = 1MB'
>>> import humansize>>> import sys>>> '1MB = 1000{0.modules[humansize].SUFFIXES[1000][0]}'.format(sys)'1MB = 1000KB'
Sys. modules is a dictionary that stores imported modules in the current python instance. The module name is the key, and the module itself is the value.
>>> s = '''finished files are the re-sults of years of scientific study combined with theexperience of years. ‘'' >>> s.splitlines()['finished files are the re-', 'sults of years of scientific study combined with the', 'experience of years. ‘] >>> print(s.lower())finished files are the re-sults of years of scientific study combined with theexperience of years.
>>> a_list = query.split("&")>>> a_list['user=pilgrim', 'database=master', ‘password=PapayaWhip'] >>> a_list_of_list = [v.split('=',1) for v in a_list]>>> a_list_of_list[['user', 'pilgrim'], ['database', 'master'], ['password', ‘PapayaWhip']] >>> a_dict = dict(a_list_of_list)>>> a_dict{'password': 'PapayaWhip', 'database': 'master', 'user': ‘pilgrim'}
Split ()-separates strings into a string list based on the specified delimiter.
Dict ()-converts a list containing a list to a dictionary object
String fragment
>>> a_string = "My alphabet starts where your alphabet ends.">>> a_string[3:11]‘alphabet' >>> a_string[3:-3]'alphabet starts where your alphabet en’ >>> a_string[:18]'My alphabet starts’ >>> a_string[18:]' where your alphabet ends.'
String VS. Bytes
Bytes object definition: B ', eg: by = B' abcd \ x65'
The value of a Bytes object cannot be changed. However, you can use the built-in function bytearry () to convert a bytes object to a bytearry object. The value of a bytearry object can be changed.
>>> by = b'abcd\x65'>>> barr = bytearray(by)>>> barrbytearray(b'abcde') >>> barr[0]=102>>> barrbytearray(b'fbcde')
>>> a_string = "dive into python">>> by = a_string.encode('utf-8')>>> byb'dive into python'>>> roundtrip = by.decode('big5')>>> roundtrip'dive into python'
String. encode () -- uses a certain encoding method as a parameter to convert a string to a bytes object.
Bytes. decode () -- uses a certain encoding method as a parameter to convert a bytes object to a string object.