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

前端 未结 9 770
醉梦人生
醉梦人生 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:37

    Here's an example where the absence of b would throw a TypeError exception in Python 3.x

    >>> f=open("new", "wb")
    >>> f.write("Hello Python!")
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: 'str' does not support the buffer interface
    

    Adding a b prefix would fix the problem.

提交回复
热议问题