bytes.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # literals
  2. print(b'123')
  3. print(br'123')
  4. print(rb'123')
  5. print(b'\u1234')
  6. # construction
  7. print(bytes())
  8. print(bytes(b'abc'))
  9. # make sure empty bytes is converted correctly
  10. print(str(bytes(), 'utf-8'))
  11. a = b"123"
  12. print(a)
  13. print(str(a))
  14. print(repr(a))
  15. print(a[0], a[2])
  16. print(a[-1])
  17. print(str(a, "utf-8"))
  18. print(str(a, "utf-8", "ignore"))
  19. try:
  20. str(a, "utf-8", "ignore", "toomuch")
  21. except TypeError:
  22. print("TypeError")
  23. s = 0
  24. for i in a:
  25. s += i
  26. print(s)
  27. print(bytes("abc", "utf-8"))
  28. print(bytes("abc", "utf-8", "replace"))
  29. try:
  30. bytes("abc")
  31. except TypeError:
  32. print("TypeError")
  33. try:
  34. bytes("abc", "utf-8", "replace", "toomuch")
  35. except TypeError:
  36. print("TypeError")
  37. print(bytes(3))
  38. print(bytes([3, 2, 1]))
  39. print(bytes(range(5)))
  40. # Make sure bytes are not mistreated as unicode
  41. x = b"\xff\x8e\xfe}\xfd\x7f"
  42. print(len(x))
  43. print(x[0], x[1], x[2], x[3])
  44. # Make sure init values are not mistreated as unicode chars
  45. # For sequence of known len
  46. print(bytes([128, 255]))
  47. # For sequence of unknown len
  48. print(bytes(iter([128, 255])))
  49. # Shouldn't be able to make bytes with negative length
  50. try:
  51. bytes(-1)
  52. except ValueError:
  53. print('ValueError')