In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you the meaning of bytes and bytearray in python. I hope you will get something after reading this article. Let's discuss it together.
Bytes 、 bytearray
Python3 introduces two new types:
Bytes, immutable, byte sequence, can be understood as a list of bytes
Bytearray, byte array, variable, all data can be converted to byte array for processing
String and bytes:
A string is an ordered sequence of characters, which can be understood by coding
Bytes is an ordered and immutable sequence of bytes
Bytearray is an ordered variable sequence of bytes
Encode and decode:
The string encodes encode according to different character sets and returns the byte sequence bytes
Encode (encoding='utf-8',errors='strict')-- > bytes
The byte sequence decodes the decode according to different character sets and returns the string.
Bytes.decode (encoding='utf-8',errors='strict')-- > str
Bytearray.decode (encoding='utf-8',errors='stric')-- > str
Bytes definition:
Bytes (), empty bytes, useless
Bytes (int), specified byte bytes, filled with 0, int is size (the lowest bit is 1, odd, used to judge odd and even numbers)
An iterable object composed of bytes (iterable_of_ints)-- > bytes, int of [0-255], commonly used
Bytes (string,encoding [, errors])-- > bytes, equivalent to string.encode ()
Bytes (bytes_or_buffer)-- > bytes,immutable copy of bytes_or_buffer, copying a new immutable bytes object from a byte sequence or buffer
Using the b prefix definition, only basic ASCII is allowed to use character form, > broomabc9 characters, hexadecimal representation > b'\ x41\ x61'
A format that represents a sequence of bytes. The contents in quotation marks cannot be used as strings.
Example:
In [2]: bytes (range)
Out [2]: B'\ X00\ X01\ X02\ X03\ x04\ x05\ X06\ X07\ X08\ t\ n\ X0b\ X0c\ r\ X0f\ x10\ x11\ x13\ x14\ x16\ x17\ x18\ x1a\ x1b\ x1c\ x1d\ x1f! "# $% &\'() * +, -. / 0123456789MNOPQRSTUVWYZ [\] ^ ^ _ abc'
In [3]: bytes (range (1000)) # over 255,
ValueError Traceback (most recent call last)
In ()
-> 1 bytes (range (1000))
ValueError: bytes must be in range (0256)
In [4]: bytes ([1rect 3je 5]) # 1je 3je 5 is the part in front of ASCII
Out [4]: B'\ X01\ x03\ x05'
In [5]: bytes ([91 dint 93jue 95])
Out [5]: B'[] _'
In [7]: bytes ('abc','utf8') # bytes (string,encoding [, errors]), either utf8 or utf-8
Out [7]: breadabc'
In [8]: bytes ('abc','utf-8')
Out [8]: breadabc'
In [9]: s1='abc'.encode () # commonly used
In [10]: type (S1)
Out [10]: bytes
In [11]: s1.decode ()
Out [11]: 'abc'
In [12]: s2=bytes (S1)
In [13]: S1 = = S2 # = = compare content
Out [13]: True
In [14]: id (S1) is id (S2) # is compare memory addresses
Out [14]: False
In [15]: type (S2)
Out [15]: bytes
Bytes operation:
Similar to str, they are immutable types, so many methods are the same, except that the input is bytes and the output is bytes.
Bytes.fromhex (string), class methods, methods of objects (class methods) in python are equivalent to static methods in python, static methods in python are another concept, string must be in hexadecimal form of 2 characters, and the space '6162 6a6b' will be ignored
Hex (), which returns a string in hexadecimal representation
Index, bounded abcdef' [2]-- > int, returns the number corresponding to the byte, int type
Example:
In [16]: b'abcdef'.replace (baked fame and baggage k')
Out [16]: baked abcdek'
In [17]: b'abc'.find (breadb')
Out [17]: 1
In [18]: b'abc'.split (breadb')
Out [18]: [baked, baked c']
In [19]: bytes.fromhex ('6162 096a 6b00')
Out [19]: b'ab\ tjk\ x00'
In [20]: b'abc'.hex ()
Out [20]: '616263'
In [21]: 'abc'.encode (). Hex ()
Out [21]: '616263'
In [22]: baked abcdef' [2]
Out [22]: 99
Bytearray definition:
Bytearray (), empty bytearray
Bytearray (int), which specifies the bytes of the byte, filled with 0
Bytearray (iterable_of_ints)-- iterable object composed of int of > bytearray,
Bytearray (string,encoding [, errors])-- > bytearray, which approximates string.encode (), but returns a bytearray mutable object
Bytearray (bytes_or_buffer), copying a new mutable bytearray object from a byte sequence or buffer
Note: the type defined by the b prefix is the bytes type, and there is no prefix to specify the bytearray type
Bytearray operation:
It is the same as the method of bytes type, but there are some methods of variable type.
Bytearray.fromhex (string), string must be in 2-character hexadecimal form, '6162 6a6b' space will be ignored
Hex (), which returns a string in hexadecimal representation
Append (int)
Insert (index,int)
Extend (iterable_of_ints), which appends an iterable collection of integers to the current bytearray
Pop (index=-1), which removes elements from the specified index and removes them from the tail by default
Remove (value), the first value removed was found, and the exception throwing ValueError was not found
Note: append (), insert (), extend (), pop (), remove (), these methods use the int type, with values in [0255]
Clear (), clear bytearray
Reverse (), flip bytearray, modify in place
Example:
In [23]: bytearray (baked abcdef'). Replace (baked, faded, written, baked k')
Out [23]: bytearray (baked abcdek')
In [24]: bytearray (breadabc'). Find (breadb')
Out [24]: 1
In [25]: bytearray.fromhex ('6162 09 6a 6b00')
Out [25]: bytearray (b'ab\ tjk\ x00')
In [26]: bytearray ('abc'.encode ()) .hex ()
Out [26]: '616263'
In [27]: b1=bytearray ()
In [28]: b1.append (97)
In [29]: b1
Out [29]: bytearray (breada')
In [30]: b1.append (98)
In [31]: b1
Out [31]: bytearray (baked ab')
In [33]: b1.insert (19998)
In [34]: b1
Out [34]: bytearray (baked abb')
In [35]: b1.extend ([65 pr. 66. 67])
In [36]: b1
Out [36]: bytearray (baked abbABC')
In [37]: b1.remove (66)
In [38]: b1
Out [38]: bytearray (baked abbAC')
In [39]: b1.pop ()
Out [39]: 67
In [40]: b1.reverse ()
In [41]: b1
Out [41]: bytearray (baked Abba')
In [42]: b1.clear ()
Linear structure (queuing, sequential structure, sequence sequence): iterable for...in;len (), can get the length, count outside, O (1), _ _ double underscore beginning method; can be accessed by subscript; can be sliced
Linear structure learned: list,tuple,str,bytes,bytearray
Slice:
Access a piece of data with a linear structure through an index interval
Sequence [start:stop], which represents the subsequence that returns the [start,stop] interval, excluding characters with index stop
Support for negative index
If start is 0, it can be ignored. Start must be on the left of stop.
Stop is the end, can be saved
Beyond the upper bound (right boundary), take to the end; beyond the lower bound (left boundary), take the beginning; pay attention to the direction, understood as one-dimensional x axis->, the direction from left to right
[:], which means that all elements are taken out from beginning to end, which is equivalent to the copy () method
[start:stop:step], step size slice. Step is a step size, which can be a positive or negative integer. By default, 1 start:stop step should be in the same direction as the step, otherwise an empty sequence will be returned.
Example:
In [1]: slots www.magedu.com'
In [2]: s [4:10]
Out [2]: 'magedu'
In [3]: s [: 10]
Out [3]: 'www.magedu'
In [4]: s [4:]
Out [4]: 'magedu.com'
In [5]: s [:]
Out [5]: 'www.magedu.com'
In [6]: s [:-1] # does not include the last character
Out [6]: 'www.magedu.co'
In [7]: b1roombaked www.magedu.com'
In [8]: b1 [- 40:40]
Out [8]: baked www.magedu.com'
In [9]: bytearray (b1) [- 40:40]
Out [9]: bytearray (baked www.magedu.com')
In [10]: bytearray (b1) [- 40:4]
Out [10]: bytearray
In [11]: bytearray (b1) [- 10 muri 4]
Out [11]: bytearray (breadmagedu')
In [12]: bytearray (b1) [- 10 Murray 12]
Out [12]: bytearray (baked')
In [13]: s
Out [13]: 'www.magedu.com'
In [14]: s [4:10:2]
Out [14]: 'mgd'
In [15]: s [4: 10]
Out [15]:''
In [16]: s [- 10 Murray 4muri 2]
Out [16]:''
In [17]: s [- 4Rose 10Vl2]
Out [17]:''
In [18]: s [- 4WR UL10RUL 2] # find it in reverse order and print it backwards
Out [18]: '.dg'
Encapsulation & deconstruction:
It is different from unpacking in java.
The unique grammar of python is learned and used for reference by many languages.
Encapsulation:
Separate multiple values with commas and group them together
In essence, a tuple is returned, but parentheses are omitted
Deconstruct:
Unravel the elements of the linear structure and assign them to other variables sequentially
The number of variables accepted on the left should be the same as the number of unlocked elements on the right.
Deconstruction is a good function provided by python. It is convenient to extract the values of complex data structures, and it will be more convenient to use with _ discard variables.
Deconstruction of python3:
Use * variable name to receive, but cannot be used alone, nor can you use > = 2 times, otherwise you can't tell which variable is assigned more.
Collected by * variable names to form a list
Example:
In [1]: T1 = (1je 2) # is defined as tuple
In [2]: 2 # encapsulate 1 and 2 into tuple, commonly used, syntax sugar, encapsulation priority tuple, deconstruction priority list
In [3]: type (T1)
Out [3]: tuple
In [4]: type (T2)
Out [4]: tuple
Example:
In [6]: axi4
In [7]: bread5
In [8]: temp=a
In [9]: Abacb
In [10]: these three sentences are equivalent to temp=b,a;a,b=temp and temp=b,a;a,b=temp.
In [11]: a
Out [11]: 5
In [12]: b
Out [12]: 4
Example:
In [13]: axi4
In [14]: bread5
In [15]: temp=b,a
In [16]: a <...
In [17]: a
Out [17]: 5
In [18]: b
Out [18]: 4
Example:
In [17]: a
Out [17]: 5
In [18]: b
Out [18]: 4
In [19]: a ~ # is commonly used, encapsulated on the right (first encapsulated into tuple), and deconstructed on the left (re-assigned)
In [20]: a
Out [20]: 4
In [21]: b
Out [21]: 5
Example:
In [22]: lst= [3,5]
In [23]: first,second=lst
In [24]: print (first,second)
3 5
In [25]: a _
In [26]: a _
In [27]: a _ b = [1 _ 2]
In [28]: a
Out [28]: 1
In [29]: b
Out [29]: 2
In [30]: a ~ (10) ~ (th) b = {10 ~ (th)) ~ (20)} # nonlinear structure
In [31]: a
Out [31]: 10
In [32]: b
Out [32]: 20
In [33]: a key b = {'axiaqizhuo 10 # nonlinear structure, passing the dictionary's key to an and b
In [34]: a
Out [34]:'b'
In [35]: b
Out [35]:'a'
In [36]: a list, 3, 4, 5 # b for list
In [37]: a
Out [37]: 1
In [38]: b
Out [38]: [2, 3, 4, 5]
In [39]: [list b] = (1) # although there is a list structure on the left, it is not assigned to a variable. It only assigns a value to the arecine b variable in the list structure
In [40]: a
Out [40]: 1
In [41]: b
Out [41]: 2
In [42]: [a _ r _ b] = 1pm _ 2
In [43]: (a) b) = 30 and 40
In [44]: a
Out [44]: 30
In [45]: b
Out [45]: 40
In [46]: lst=list (range (1meme 101))
In [47]: head,*mid,tail=lst
In [48]: * lst2=lst # python3 deconstruction * variable name cannot be used alone, it can be written as lst2=lst
File "", line 1
* lst2=lst
^
SyntaxError: starred assignment target must be in a list or tuple
In [51]: head,*mid1,*mid2,tail=lst # can't tell the difference between * mid1 and * mid2
File "", line 1
Head,*mid1,*mid2,tail=lst
^
SyntaxError: two starred expressions in assignment
_ discard variables:
If you don't care about a variable, you can define to change the name of the variable to _
This is a convention, an unwritten rule, not a standard.
_ is a legal identifier and can also be used as a valid variable, but defined as _, I hope it will not be used unless you explicitly know that this data needs to be used.
This variable itself does not have any meaning and readability, so it is not used for human use. Many libraries in python use this variable, and it is widely used. Please do not use _ without knowing the scope of the variable, resulting in a conflict with the library.
Example:
In [52]: head,*mid,tail='abcdefghijklmn'
In [53]: type (mid)
Out [53]: list
In [54]: lst= [9,8,7,6,5]
In [55]: head,*_,tail=lst
In [56]: print (_)
[8, 7, 6]
In [57]: _, * _, tail=lst # _ is the same variable. If overridden, the assignment is defined.
In [58]: print (_)
[8, 7, 6]
After reading this article, I believe you have a certain understanding of "what is the meaning of bytes and bytearray in python". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.