当我在 Python 3.8.0 中编码字符串时如何删除 b' 和 '?

How to remove b' and ' when I encode a String in Python 3.8.0?

我在 python 3.8.0 中使用 UDP,但是我的消息有问题,一旦套接字不允许字符串,我必须将字符串转换为二进制,所以我使用了 message.encode(),但它在消息末尾带有额外的 b' 和 ',我该如何删除它们?

我的代码:

import socket
import sys
import config

MY_IP = config.myIP
OTHER_IP = config.otherIp
PORT_NUMBER = config.port_number

# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

server_address = (MY_IP, PORT_NUMBER)
message = input("Write a message: ").encode( )
print("Message: ", message)

您可以在下面看到结果的输出:

Write a message: a
Message:  b'a' 

还有其他方法可以将字符串转换为二进制吗?

新 python 学习者谢谢你。

b'...' 正是 python 表示字节类型的方式。例如:

my_string = "This is my string."
type(my_string) # str type

encoded_string = my_string.encode()
type(encoded_string) # bytes type, when printing represented by leading b

您可以使用内置 .decode() 方法将 bytes 类型转换回 str:

decoded_string = encoded_string.decode()
type(decoded_string) # str type

额外:

您还可以指定 .encode().decode() 使用的编码字符集:

hello_encoded = "Hello".encode("ascii") # bytes type
hello_decoded = hello_encoded.decode("ascii") # str type

当使用 utf-8 编码时,您可以编写各种花哨的字符(那些不能使用 ascii 编码的字符,会抛出错误):

fancy_chars_encoded = "© ½ £ 4²".encode("utf-8")
fancy_chars_decoded = fancy_chars_encoded.decode("utf-8")

此外,utf-8 是在没有将字符集传递给 .encode().decode() 时使用的默认字符集。

你做对了。而这个b仅仅表示这个字符串是byte。这不是您的变量的一部分。例如:

>>> a = "abc".encode()
>>> print(a)
b'abc'
>>> print(len(a))
3 # not 6
>>> print(a[0])
'a' # not b