What does the 'b' character do in front of a string literal?

前端 未结 9 774
醉梦人生
醉梦人生 2020-11-21 05:07

Apparently, the following is the valid syntax:

my_string = b\'The string\'

I would like to know:

  1. What does this b
9条回答
  •  独厮守ぢ
    2020-11-21 05:17

    In addition to what others have said, note that a single character in unicode can consist of multiple bytes.

    The way unicode works is that it took the old ASCII format (7-bit code that looks like 0xxx xxxx) and added multi-bytes sequences where all bytes start with 1 (1xxx xxxx) to represent characters beyond ASCII so that Unicode would be backwards-compatible with ASCII.

    >>> len('Öl')  # German word for 'oil' with 2 characters
    2
    >>> 'Öl'.encode('UTF-8')  # convert str to bytes 
    b'\xc3\x96l'
    >>> len('Öl'.encode('UTF-8'))  # 3 bytes encode 2 characters !
    3
    

提交回复
热议问题