ascii.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. """Constants and membership tests for ASCII characters"""
  2. NUL = 0x00 # ^@
  3. SOH = 0x01 # ^A
  4. STX = 0x02 # ^B
  5. ETX = 0x03 # ^C
  6. EOT = 0x04 # ^D
  7. ENQ = 0x05 # ^E
  8. ACK = 0x06 # ^F
  9. BEL = 0x07 # ^G
  10. BS = 0x08 # ^H
  11. TAB = 0x09 # ^I
  12. HT = 0x09 # ^I
  13. LF = 0x0a # ^J
  14. NL = 0x0a # ^J
  15. VT = 0x0b # ^K
  16. FF = 0x0c # ^L
  17. CR = 0x0d # ^M
  18. SO = 0x0e # ^N
  19. SI = 0x0f # ^O
  20. DLE = 0x10 # ^P
  21. DC1 = 0x11 # ^Q
  22. DC2 = 0x12 # ^R
  23. DC3 = 0x13 # ^S
  24. DC4 = 0x14 # ^T
  25. NAK = 0x15 # ^U
  26. SYN = 0x16 # ^V
  27. ETB = 0x17 # ^W
  28. CAN = 0x18 # ^X
  29. EM = 0x19 # ^Y
  30. SUB = 0x1a # ^Z
  31. ESC = 0x1b # ^[
  32. FS = 0x1c # ^\
  33. GS = 0x1d # ^]
  34. RS = 0x1e # ^^
  35. US = 0x1f # ^_
  36. SP = 0x20 # space
  37. DEL = 0x7f # delete
  38. controlnames = [
  39. "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
  40. "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
  41. "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
  42. "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US",
  43. "SP"
  44. ]
  45. def _ctoi(c):
  46. if type(c) == type(""):
  47. return ord(c)
  48. else:
  49. return c
  50. def isalnum(c): return isalpha(c) or isdigit(c)
  51. def isalpha(c): return isupper(c) or islower(c)
  52. def isascii(c): return _ctoi(c) <= 127 # ?
  53. def isblank(c): return _ctoi(c) in (8,32)
  54. def iscntrl(c): return _ctoi(c) <= 31
  55. def isdigit(c): return _ctoi(c) >= 48 and _ctoi(c) <= 57
  56. def isgraph(c): return _ctoi(c) >= 33 and _ctoi(c) <= 126
  57. def islower(c): return _ctoi(c) >= 97 and _ctoi(c) <= 122
  58. def isprint(c): return _ctoi(c) >= 32 and _ctoi(c) <= 126
  59. def ispunct(c): return _ctoi(c) != 32 and not isalnum(c)
  60. def isspace(c): return _ctoi(c) in (9, 10, 11, 12, 13, 32)
  61. def isupper(c): return _ctoi(c) >= 65 and _ctoi(c) <= 90
  62. def isxdigit(c): return isdigit(c) or \
  63. (_ctoi(c) >= 65 and _ctoi(c) <= 70) or (_ctoi(c) >= 97 and _ctoi(c) <= 102)
  64. def isctrl(c): return _ctoi(c) < 32
  65. def ismeta(c): return _ctoi(c) > 127
  66. def ascii(c):
  67. if type(c) == type(""):
  68. return chr(_ctoi(c) & 0x7f)
  69. else:
  70. return _ctoi(c) & 0x7f
  71. def ctrl(c):
  72. if type(c) == type(""):
  73. return chr(_ctoi(c) & 0x1f)
  74. else:
  75. return _ctoi(c) & 0x1f
  76. def alt(c):
  77. if type(c) == type(""):
  78. return chr(_ctoi(c) | 0x80)
  79. else:
  80. return _ctoi(c) | 0x80
  81. def unctrl(c):
  82. bits = _ctoi(c)
  83. if bits == 0x7f:
  84. rep = "^?"
  85. elif isprint(bits & 0x7f):
  86. rep = chr(bits & 0x7f)
  87. else:
  88. rep = "^" + chr(((bits & 0x7f) | 0x20) + 0x20)
  89. if bits & 0x80:
  90. return "!" + rep
  91. return rep