PageRenderTime 60ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/stringold.py

https://bitbucket.org/dac_io/pypy
Python | 432 lines | 342 code | 12 blank | 78 comment | 14 complexity | 1ef2d54358e067b62e6f05e4d1c0d817 MD5 | raw file
  1. # module 'string' -- A collection of string operations
  2. # Warning: most of the code you see here isn't normally used nowadays. With
  3. # Python 1.6, many of these functions are implemented as methods on the
  4. # standard string object. They used to be implemented by a built-in module
  5. # called strop, but strop is now obsolete itself.
  6. """Common string manipulations.
  7. Public module variables:
  8. whitespace -- a string containing all characters considered whitespace
  9. lowercase -- a string containing all characters considered lowercase letters
  10. uppercase -- a string containing all characters considered uppercase letters
  11. letters -- a string containing all characters considered letters
  12. digits -- a string containing all characters considered decimal digits
  13. hexdigits -- a string containing all characters considered hexadecimal digits
  14. octdigits -- a string containing all characters considered octal digits
  15. """
  16. from warnings import warnpy3k
  17. warnpy3k("the stringold module has been removed in Python 3.0", stacklevel=2)
  18. del warnpy3k
  19. # Some strings for ctype-style character classification
  20. whitespace = ' \t\n\r\v\f'
  21. lowercase = 'abcdefghijklmnopqrstuvwxyz'
  22. uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  23. letters = lowercase + uppercase
  24. digits = '0123456789'
  25. hexdigits = digits + 'abcdef' + 'ABCDEF'
  26. octdigits = '01234567'
  27. # Case conversion helpers
  28. _idmap = ''
  29. for i in range(256): _idmap = _idmap + chr(i)
  30. del i
  31. # Backward compatible names for exceptions
  32. index_error = ValueError
  33. atoi_error = ValueError
  34. atof_error = ValueError
  35. atol_error = ValueError
  36. # convert UPPER CASE letters to lower case
  37. def lower(s):
  38. """lower(s) -> string
  39. Return a copy of the string s converted to lowercase.
  40. """
  41. return s.lower()
  42. # Convert lower case letters to UPPER CASE
  43. def upper(s):
  44. """upper(s) -> string
  45. Return a copy of the string s converted to uppercase.
  46. """
  47. return s.upper()
  48. # Swap lower case letters and UPPER CASE
  49. def swapcase(s):
  50. """swapcase(s) -> string
  51. Return a copy of the string s with upper case characters
  52. converted to lowercase and vice versa.
  53. """
  54. return s.swapcase()
  55. # Strip leading and trailing tabs and spaces
  56. def strip(s):
  57. """strip(s) -> string
  58. Return a copy of the string s with leading and trailing
  59. whitespace removed.
  60. """
  61. return s.strip()
  62. # Strip leading tabs and spaces
  63. def lstrip(s):
  64. """lstrip(s) -> string
  65. Return a copy of the string s with leading whitespace removed.
  66. """
  67. return s.lstrip()
  68. # Strip trailing tabs and spaces
  69. def rstrip(s):
  70. """rstrip(s) -> string
  71. Return a copy of the string s with trailing whitespace
  72. removed.
  73. """
  74. return s.rstrip()
  75. # Split a string into a list of space/tab-separated words
  76. def split(s, sep=None, maxsplit=0):
  77. """split(str [,sep [,maxsplit]]) -> list of strings
  78. Return a list of the words in the string s, using sep as the
  79. delimiter string. If maxsplit is nonzero, splits into at most
  80. maxsplit words If sep is not specified, any whitespace string
  81. is a separator. Maxsplit defaults to 0.
  82. (split and splitfields are synonymous)
  83. """
  84. return s.split(sep, maxsplit)
  85. splitfields = split
  86. # Join fields with optional separator
  87. def join(words, sep = ' '):
  88. """join(list [,sep]) -> string
  89. Return a string composed of the words in list, with
  90. intervening occurrences of sep. The default separator is a
  91. single space.
  92. (joinfields and join are synonymous)
  93. """
  94. return sep.join(words)
  95. joinfields = join
  96. # for a little bit of speed
  97. _apply = apply
  98. # Find substring, raise exception if not found
  99. def index(s, *args):
  100. """index(s, sub [,start [,end]]) -> int
  101. Like find but raises ValueError when the substring is not found.
  102. """
  103. return _apply(s.index, args)
  104. # Find last substring, raise exception if not found
  105. def rindex(s, *args):
  106. """rindex(s, sub [,start [,end]]) -> int
  107. Like rfind but raises ValueError when the substring is not found.
  108. """
  109. return _apply(s.rindex, args)
  110. # Count non-overlapping occurrences of substring
  111. def count(s, *args):
  112. """count(s, sub[, start[,end]]) -> int
  113. Return the number of occurrences of substring sub in string
  114. s[start:end]. Optional arguments start and end are
  115. interpreted as in slice notation.
  116. """
  117. return _apply(s.count, args)
  118. # Find substring, return -1 if not found
  119. def find(s, *args):
  120. """find(s, sub [,start [,end]]) -> in
  121. Return the lowest index in s where substring sub is found,
  122. such that sub is contained within s[start,end]. Optional
  123. arguments start and end are interpreted as in slice notation.
  124. Return -1 on failure.
  125. """
  126. return _apply(s.find, args)
  127. # Find last substring, return -1 if not found
  128. def rfind(s, *args):
  129. """rfind(s, sub [,start [,end]]) -> int
  130. Return the highest index in s where substring sub is found,
  131. such that sub is contained within s[start,end]. Optional
  132. arguments start and end are interpreted as in slice notation.
  133. Return -1 on failure.
  134. """
  135. return _apply(s.rfind, args)
  136. # for a bit of speed
  137. _float = float
  138. _int = int
  139. _long = long
  140. _StringType = type('')
  141. # Convert string to float
  142. def atof(s):
  143. """atof(s) -> float
  144. Return the floating point number represented by the string s.
  145. """
  146. if type(s) == _StringType:
  147. return _float(s)
  148. else:
  149. raise TypeError('argument 1: expected string, %s found' %
  150. type(s).__name__)
  151. # Convert string to integer
  152. def atoi(*args):
  153. """atoi(s [,base]) -> int
  154. Return the integer represented by the string s in the given
  155. base, which defaults to 10. The string s must consist of one
  156. or more digits, possibly preceded by a sign. If base is 0, it
  157. is chosen from the leading characters of s, 0 for octal, 0x or
  158. 0X for hexadecimal. If base is 16, a preceding 0x or 0X is
  159. accepted.
  160. """
  161. try:
  162. s = args[0]
  163. except IndexError:
  164. raise TypeError('function requires at least 1 argument: %d given' %
  165. len(args))
  166. # Don't catch type error resulting from too many arguments to int(). The
  167. # error message isn't compatible but the error type is, and this function
  168. # is complicated enough already.
  169. if type(s) == _StringType:
  170. return _apply(_int, args)
  171. else:
  172. raise TypeError('argument 1: expected string, %s found' %
  173. type(s).__name__)
  174. # Convert string to long integer
  175. def atol(*args):
  176. """atol(s [,base]) -> long
  177. Return the long integer represented by the string s in the
  178. given base, which defaults to 10. The string s must consist
  179. of one or more digits, possibly preceded by a sign. If base
  180. is 0, it is chosen from the leading characters of s, 0 for
  181. octal, 0x or 0X for hexadecimal. If base is 16, a preceding
  182. 0x or 0X is accepted. A trailing L or l is not accepted,
  183. unless base is 0.
  184. """
  185. try:
  186. s = args[0]
  187. except IndexError:
  188. raise TypeError('function requires at least 1 argument: %d given' %
  189. len(args))
  190. # Don't catch type error resulting from too many arguments to long(). The
  191. # error message isn't compatible but the error type is, and this function
  192. # is complicated enough already.
  193. if type(s) == _StringType:
  194. return _apply(_long, args)
  195. else:
  196. raise TypeError('argument 1: expected string, %s found' %
  197. type(s).__name__)
  198. # Left-justify a string
  199. def ljust(s, width):
  200. """ljust(s, width) -> string
  201. Return a left-justified version of s, in a field of the
  202. specified width, padded with spaces as needed. The string is
  203. never truncated.
  204. """
  205. n = width - len(s)
  206. if n <= 0: return s
  207. return s + ' '*n
  208. # Right-justify a string
  209. def rjust(s, width):
  210. """rjust(s, width) -> string
  211. Return a right-justified version of s, in a field of the
  212. specified width, padded with spaces as needed. The string is
  213. never truncated.
  214. """
  215. n = width - len(s)
  216. if n <= 0: return s
  217. return ' '*n + s
  218. # Center a string
  219. def center(s, width):
  220. """center(s, width) -> string
  221. Return a center version of s, in a field of the specified
  222. width. padded with spaces as needed. The string is never
  223. truncated.
  224. """
  225. n = width - len(s)
  226. if n <= 0: return s
  227. half = n/2
  228. if n%2 and width%2:
  229. # This ensures that center(center(s, i), j) = center(s, j)
  230. half = half+1
  231. return ' '*half + s + ' '*(n-half)
  232. # Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
  233. # Decadent feature: the argument may be a string or a number
  234. # (Use of this is deprecated; it should be a string as with ljust c.s.)
  235. def zfill(x, width):
  236. """zfill(x, width) -> string
  237. Pad a numeric string x with zeros on the left, to fill a field
  238. of the specified width. The string x is never truncated.
  239. """
  240. if type(x) == type(''): s = x
  241. else: s = repr(x)
  242. n = len(s)
  243. if n >= width: return s
  244. sign = ''
  245. if s[0] in ('-', '+'):
  246. sign, s = s[0], s[1:]
  247. return sign + '0'*(width-n) + s
  248. # Expand tabs in a string.
  249. # Doesn't take non-printing chars into account, but does understand \n.
  250. def expandtabs(s, tabsize=8):
  251. """expandtabs(s [,tabsize]) -> string
  252. Return a copy of the string s with all tab characters replaced
  253. by the appropriate number of spaces, depending on the current
  254. column, and the tabsize (default 8).
  255. """
  256. res = line = ''
  257. for c in s:
  258. if c == '\t':
  259. c = ' '*(tabsize - len(line) % tabsize)
  260. line = line + c
  261. if c == '\n':
  262. res = res + line
  263. line = ''
  264. return res + line
  265. # Character translation through look-up table.
  266. def translate(s, table, deletions=""):
  267. """translate(s,table [,deletechars]) -> string
  268. Return a copy of the string s, where all characters occurring
  269. in the optional argument deletechars are removed, and the
  270. remaining characters have been mapped through the given
  271. translation table, which must be a string of length 256.
  272. """
  273. return s.translate(table, deletions)
  274. # Capitalize a string, e.g. "aBc dEf" -> "Abc def".
  275. def capitalize(s):
  276. """capitalize(s) -> string
  277. Return a copy of the string s with only its first character
  278. capitalized.
  279. """
  280. return s.capitalize()
  281. # Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
  282. def capwords(s, sep=None):
  283. """capwords(s, [sep]) -> string
  284. Split the argument into words using split, capitalize each
  285. word using capitalize, and join the capitalized words using
  286. join. Note that this replaces runs of whitespace characters by
  287. a single space.
  288. """
  289. return join(map(capitalize, s.split(sep)), sep or ' ')
  290. # Construct a translation string
  291. _idmapL = None
  292. def maketrans(fromstr, tostr):
  293. """maketrans(frm, to) -> string
  294. Return a translation table (a string of 256 bytes long)
  295. suitable for use in string.translate. The strings frm and to
  296. must be of the same length.
  297. """
  298. if len(fromstr) != len(tostr):
  299. raise ValueError, "maketrans arguments must have same length"
  300. global _idmapL
  301. if not _idmapL:
  302. _idmapL = list(_idmap)
  303. L = _idmapL[:]
  304. fromstr = map(ord, fromstr)
  305. for i in range(len(fromstr)):
  306. L[fromstr[i]] = tostr[i]
  307. return join(L, "")
  308. # Substring replacement (global)
  309. def replace(s, old, new, maxsplit=0):
  310. """replace (str, old, new[, maxsplit]) -> string
  311. Return a copy of string str with all occurrences of substring
  312. old replaced by new. If the optional argument maxsplit is
  313. given, only the first maxsplit occurrences are replaced.
  314. """
  315. return s.replace(old, new, maxsplit)
  316. # XXX: transitional
  317. #
  318. # If string objects do not have methods, then we need to use the old string.py
  319. # library, which uses strop for many more things than just the few outlined
  320. # below.
  321. try:
  322. ''.upper
  323. except AttributeError:
  324. from stringold import *
  325. # Try importing optional built-in module "strop" -- if it exists,
  326. # it redefines some string operations that are 100-1000 times faster.
  327. # It also defines values for whitespace, lowercase and uppercase
  328. # that match <ctype.h>'s definitions.
  329. try:
  330. from strop import maketrans, lowercase, uppercase, whitespace
  331. letters = lowercase + uppercase
  332. except ImportError:
  333. pass # Use the original versions