python2.7和python 3.4中的ord函数是否不同?

ord function in python2.7 and python 3.4 are different?

我一直在运行一个脚本,在其中使用ord()函数,并且出于python 2.7中的任何原因,它接受unicode字符串字符,并输出一个整数。

在python 3.4中,情况并非如此。这是产生的错误的输出:

1
2
3
4
Traceback (most recent call last):
  File"udpTransfer.py", line 38, in <module>
    buf.append(ord(c))
TypeError: ord() expected string of length 1, but int found

当我查看两个文档时,都将ord函数解释为做同样的事情。

这是我用于两个python版本的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import socket,sys, ast , os, struct
from time import ctime
import time
import csv


# creating the udo socket necessary to receive data
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
ip = '192.168.10.101' #i.p. of our computer
port = 20000 # socket port opened to connect from the matlab udp send data stream
server_address = (ip, port)

sock.bind(server_address)   # bind socket

sock.settimeout(2)          # sock configuration
sock.setblocking(1)
print('able to bind')
ii = 0
shotNummer = 0
client = ''
Array = []
byte = 8192
filename = time.strftime("%d_%m_%Y_%H-%M-%S")
filename = filename + '.csv'
try :
    with open(filename,'wb') as csvfile :
        spamwriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
        # spamwriter.writerow((titles))
        # as long as data comes in, well take it
        while True:
            data,client = sock.recvfrom(byte)
            buf = []
            values = []
            for c in data:
                # print(type(c))
                buf.append(ord(c))
                if len(buf) == 4 :
                    ###

有谁能解释为什么python3.4会说c是一个整数,而不是在Python 2.7中实际上是一个字符串,就像ord()函数所要求的那样?


您正在将整数传递给Python 3中的ord(),这是因为您要遍历Python 3中的bytes对象(元组中第一个元素从socket.recvfrom()返回值):

1
2
3
4
5
6
>>> for byte in b'abc':
...     print(byte)
...
97
98
99

来自bytes类型文档:

While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers[.]

Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer [...].

在Python 2中,socket.recvfrom()改为生成一个str对象,并且在该对象上进行迭代会生成新的单字符字符串对象,确实需要将其传递给ord()才能转换为整数。铅>

您可以改用bytearray()在Python 2和3中获得相同的整数序列。

1
2
for c in bytearray(data):
    # c is now in integer in both Python 2 and 3

在这种情况下,您根本不需要使用ord()


我认为区别是在Python 3中,sock.recvfrom(...)调用返回字节,而Python 2.7 recvfrom返回字符串。因此ord并没有改变,但是传递给ord的东西已经改变。

Python 2.7 recvfrom

Python 3.5 recvfrom