Python3 in bytes and strings
Only one data type in Python3 can hold text information, which is str (string), which is an immutable sequence, and the Unicode code bit is saved. In Python3, the bytes object is used to process the byte string.
Unlike str, bytes and mutable bytearray can only use bytes as the sequence value, which is an integer representation between 0~256.
print(bytes([101,100,99]))
b‘edc‘
list(b‘hello‘)
[104, 101, 108, 108, 111]
list(b‘he llo‘)
[104, 101, 32, 32, 32, 108, 108, 111]#空格的序列值是32
Starting with python3.0, all strings without a prefix are Unicode. byte string to prefix B
Unicode strings are literals that cannot be represented in bytes, and data is saved to text or sent over the network must be binary data, so the string object must be encoded as a sequence of bytes
String to byte sequence:
1. Str.encode (encoding,errors) method, encoding is the codec, the default value is ' Utf-8 '
‘hello‘.encode() b‘hello‘
-
Bytes (source,encoding,errors) constructor, creates a new byte sequence, source is a string, encoding is a codec, must be specified encoding, no default value
Bytes (' Hello ', encoding= ' utf-8 ')
B ' Hello '
Bytes (' Hello ', ' utf-8 ')
B ' Hello '
Converts binary data represented by bytes to a string
-
Bytes.decode (Encoding,errors) method, encoding must be the same as encoding in Str.encode
B ' Hello '. Decode ()
' Hello '
-
The Str (SOURCE,ENCODING,ERROR) constructor is similar to the bytes () constructor, where source is a sequence of bytes and must specify the parameter encoding of the STR function, which has no default value
Str (b ' Hello ', ' utf-8 ')
' Hello '
The Python string is immutable, the bytes byte sequence is immutable, there are pros and cons, and the advantage is that the string can do the key or set element of the dictionary, since the value of the initialization string does not change. The disadvantage is that when you want to modify a string, you need to create a completely new instance of the string. ByteArray bytes variable version, byte array can be added by Append,pop,insert and other methods to modify the deleted byte sequence
Handling string concatenation
-
Using the + = method
S= "" For sub in Subs:s+=sub
-
Using the Join method
S= "". Join (Subs)
Formatting methods for strings Str.format or%
Python string and byte sequence