Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have been running a script where I use the ord() function and for whatever the reason in python 2.7, it accepts the unicode string character just as it requires and outputs an integer.

In python 3.4, this is not so much the case. This is the output of error that is being produced :

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

When I look in both documentations, the ord function is explained to be doing the same exact thing.

This is the code that I am using for both python versions:

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 :
                    ###

Can anyone explain why python3.4 it says that c is an integer, rather than in Python 2.7 where it is actually a string, just as the ord() function requires?

like image 989
Aboogie Avatar asked Aug 23 '16 13:08

Aboogie


People also ask

What is the difference between Python 2.7 and Python 3?

Python 2.7 (last version in 2. x ) is no longer under development and in 2020 will be discontinued. Python 3 is a newer version of the Python programming language which was released in December 2008. This version was mainly released to fix problems that exist in Python 2.

How can you tell the difference between Python 2 and 3?

In Python 3, print is considered to be a function and not a statement. In Python 2, strings are stored as ASCII by default. In Python 3, strings are stored as UNICODE by default. On the division of two integers, we get an integral value in Python 2.

What is Ord in Python 3?

Python ord() Function The ord() function returns the number representing the unicode code of a specified character.

Are Python 2 and 3 compatible with each other?

# Python 2 and 3: forward-compatible from builtins import range for i in range(10**8): ... # Python 2 and 3: backward-compatible from past.


2 Answers

You are passing in an integer to ord() in Python 3. That's because you are iterating over a bytes object in Python 3 (the first element in the tuple return value from socket.recvfrom()):

>>> for byte in b'abc':
...     print(byte)
...
97
98
99

From the bytes type documentation:

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

and

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

In Python 2, socket.recvfrom() produces a str object instead, and iteration over such an object gives new one-character string objects, which indeed need to be passed to ord() to be converted to an integer.

You could instead use a bytearray() here to get the same integer sequence in both Python 2 and 3:

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

You don't need to use ord() at all in that case.

like image 94
Martijn Pieters Avatar answered Nov 14 '22 23:11

Martijn Pieters


I think the difference is that in Python 3 the sock.recvfrom(...) call returns bytes while Python 2.7 recvfrom returns a string. So ord did not change but what is being passed to ord has changed.

Python 2.7 recvfrom

Python 3.5 recvfrom

like image 41
Liam Kelly Avatar answered Nov 14 '22 21:11

Liam Kelly