【问题标题】:Python bytearray to send unicode between socketsPython bytearray 在套接字之间发送 unicode
【发布时间】:2023-03-22 00:52:01
【问题描述】:

我已经设置了我的两个第一个套接字。在客户端,我想发送 unicode 字符串。然后在服务器端,我将创建字符串 .upper() 并将其返回以进行打印。我设法用服务器端的一行代码做到了这一点:

modifiedMessage = message.decode('utf8').upper().encode('utf8') 

现在我想通过使用这个函数来做到这一点:

def unicodeBin(message):
utf8_byte_array = bytearray(format(message))
uba = []
for n in range (len(format(message))):
    uba.append("{0:08b}".format(utf8_byte_array[n]))
    modifiedMessage = ' '.join(uba)
return modifiedMessage

我对这段代码不太了解,因为我们刚在我的大学里开始使用 python,但我了解了大部分。我已经阅读了 bytearray 函数等。

有没有办法可以在最后一段代码中添加 .upper() 以大写我发送的消息,然后返回它,同时是 unicode?​​p>

【问题讨论】:

    标签: python sockets unicode


    【解决方案1】:
    In [1]: "a string".encode("utf-8")
    Out[1]: 'a string'
    
    In [2]: "a string".upper().encode("utf-8")
    Out[2]: 'A STRING'
    
    In [3]: "a string".encode("utf-8").upper()
    Out[3]: 'A STRING'
    
    In [4]: u"a string".upper()
    Out[4]: u'A STRING'
    
    In [5]: "a string".decode("utf-8").upper()
    Out[5]: u'A STRING'
    
    In [6]: u"a string".encode("utf-8").upper()
    Out[6]: 'A STRING'
    
    In [7]: u"a string".encode("utf-8").upper().decode("utf-8")
    Out[7]: u'A STRING'
    

    顺便说一句,那是 Python 2.7。我不太明白为什么您需要介于两者之间的所有解码和编码。 Unicode 字符串的行为方式与 Python 2.7 中的 ASCII 字符串相同,在 Python 3 中,字节和字节数组序列仍然具有 .lower() 和 .upper() 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多