Converting Python2 syntax to Python3


m3rcer

Most commonly you will encounter errors while interpretation of byte objects to string objects. Just know to convert most of the byte objects to string for Python3 syntax and you’re good most times.

Unicode

  • In Python 2, an implicit str type is ASCII. But in Python 3.x implicit str type is Unicode, meaning:
    • In python2 Bytes is same as str.
    • In Python3 Bytes and str are different.

For String to Byte Operations and vice versa

  • Remember:
    • str(variable) converts variable to a string.
    • byte(variable) converts variable to a bytes object.
  • Also:
    • variable.decode() converts a variable to a string.
    • variable.encode() converts variable to a bytes object.

For user supplied inputs

  • Python2 uses the raw_input() function.
  • Python3 uses the input() function.
  • Python2 uses the syntax: print "I Am a Sexy Hacker"
  • Python3 uses the syntax; print("I Am a Sexy Hacker")

Division Operator

  • If we are porting our code or executing python 3.x code in python 2.x, it can be dangerous if integer division changes go unnoticed (since it doesn’t raise any error). It is preferred to use the floating value (like 7.0/5 or 7/5.0) to get the expected result when porting our code.

Resources

  • https://www.pythonconverter.com/
  • https://github.com/dhocker/convert23
  • https://github.com/python