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

前端 未结 9 772
醉梦人生
醉梦人生 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 "<stdin>", line 1, in <module>
    TypeError: 'str' does not support the buffer interface
    

    Adding a b prefix would fix the problem.

    0 讨论(0)
  • 2020-11-21 05:39

    The answer to the question is that, it does:

    data.encode()
    

    and in order to decode it(remove the b, because sometimes you don't need it)

    use:

    data.decode())
    
    0 讨论(0)
  • 2020-11-21 05:42

    From server side, if we send any response, it will be sent in the form of byte type, so it will appear in the client as b'Response from server'

    In order get rid of b'....' simply use below code:

    Server file:

    stri="Response from server"    
    c.send(stri.encode())
    

    Client file:

    print(s.recv(1024).decode())
    

    then it will print Response from server

    0 讨论(0)
提交回复
热议问题