Advertisement
here2share

# b_test_Py2_to_py3.py

Dec 25th, 2021
1,227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. # print
  4. print 123
  5. print 123,
  6.  
  7. # dictionary
  8. mydict = {"name": "John Doe", "age": 30}
  9. for key in mydict.keys():
  10.     print key
  11.  
  12. for value in mydict.values():
  13.     print value
  14.  
  15. for key, value in mydict.iteritems():
  16.     print key, value
  17.  
  18. # raw_input => input
  19. name = raw_input("What is your name: ")
  20. print name
  21.  
  22. # StringIO
  23. import StringIO
  24.  
  25. stream = StringIO.StringIO("A string input.")
  26. print stream.read()
  27.  
  28. # xrange => range
  29. for i in xrange(1, 5):
  30.     print i,
  31.  
  32. # map, filter, reduce, zip operations
  33. my_list = ["1", "22", "333", "4444"]
  34. my_list_mapped = map(int, my_list)
  35. my_list_filtered = filter(lambda x: x < 10 or x > 100, my_list_mapped)
  36. my_list_reduced = reduce(lambda x, y: x + y, my_list_filtered)
  37. my_list_zip = zip(my_list, xrange(4))
  38.  
  39. # Class
  40. class MyClass:
  41.     def __init__(self, name):
  42.         self.name = name
  43.  
  44.     def __str__(self):
  45.         return self.name
  46.  
  47. # Iterator
  48. class MyIterator:
  49.     def __init__(self, iterable):
  50.         self._iter = iter(iterable)
  51.  
  52.     def next(self):
  53.         return self._iter.next()
  54.  
  55.     def __iter__(self):
  56.         return self
  57.  
  58. my_iterator = MyIterator([1, 2, 4, 5])
  59. my_iterator.next()
  60. print my_iterator
  61.  
  62. # exception
  63. try:
  64.     b = 1 / 2.0
  65.     c = 1 / 0
  66. except ZeroDivisionError, e:
  67.     print str(e)
  68.  
  69. # Attention here. This can not be automatically done properly and
  70. # will break your code.
  71. # bytes and unicode
  72. assert isinstance("a regular string", bytes)
  73. assert isinstance(u"a unicode string", unicode)
  74. assert isinstance("a regular string", basestring)
  75.  
  76. # string codec: encodeing and decoding
  77. my_bytes1 = "\xc3\x85, \xc3\x84, and \xc3\x96"
  78. my_unicode1 = my_bytes1.decode("utf-8")
  79. assert isinstance(my_bytes1, bytes)
  80. assert isinstance(my_unicode1, unicode)
  81.  
  82. my_unicode2 = u"Å, Ä, and Ö"
  83. my_bytes2 = my_unicode2.encode("utf-8")
  84. assert isinstance(my_unicode2, unicode)
  85. assert isinstance(my_bytes2, bytes)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement