PageRenderTime 38ms CodeModel.GetById 8ms RepoModel.GetById 1ms app.codeStats 0ms

/python/lib/Lib/string.py

http://github.com/JetBrains/intellij-community
Python | 529 lines | 521 code | 3 blank | 5 comment | 1 complexity | 3b08736446fc80dbfb1f76d33d1848a9 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, MPL-2.0-no-copyleft-exception, MIT, EPL-1.0, AGPL-1.0
  1. """A collection of string operations (most are no longer used).
  2. Warning: most of the code you see here isn't normally used nowadays.
  3. Beginning with Python 1.6, many of these functions are implemented as
  4. methods on the standard string object. They used to be implemented by
  5. a built-in module called strop, but strop is now obsolete itself.
  6. Public module variables:
  7. whitespace -- a string containing all characters considered whitespace
  8. lowercase -- a string containing all characters considered lowercase letters
  9. uppercase -- a string containing all characters considered uppercase letters
  10. letters -- a string containing all characters considered letters
  11. digits -- a string containing all characters considered decimal digits
  12. hexdigits -- a string containing all characters considered hexadecimal digits
  13. octdigits -- a string containing all characters considered octal digits
  14. punctuation -- a string containing all characters considered punctuation
  15. printable -- a string containing all characters considered printable
  16. """
  17. # Some strings for ctype-style character classification
  18. whitespace = ' \t\n\r\v\f'
  19. lowercase = 'abcdefghijklmnopqrstuvwxyz'
  20. uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  21. letters = lowercase + uppercase
  22. ascii_lowercase = lowercase
  23. ascii_uppercase = uppercase
  24. ascii_letters = ascii_lowercase + ascii_uppercase
  25. digits = '0123456789'
  26. hexdigits = digits + 'abcdef' + 'ABCDEF'
  27. octdigits = '01234567'
  28. punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
  29. printable = digits + letters + punctuation + whitespace
  30. # Case conversion helpers
  31. # Use str to convert Unicode literal in case of -U
  32. l = map(chr, xrange(256))
  33. _idmap = str('').join(l)
  34. del l
  35. # Functions which aren't available as string methods.
  36. # Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
  37. def capwords(s, sep=None):
  38. """capwords(s, [sep]) -> string
  39. Split the argument into words using split, capitalize each
  40. word using capitalize, and join the capitalized words using
  41. join. Note that this replaces runs of whitespace characters by
  42. a single space.
  43. """
  44. return (sep or ' ').join([x.capitalize() for x in s.split(sep)])
  45. # Construct a translation string
  46. _idmapL = None
  47. def maketrans(fromstr, tostr):
  48. """maketrans(frm, to) -> string
  49. Return a translation table (a string of 256 bytes long)
  50. suitable for use in string.translate. The strings frm and to
  51. must be of the same length.
  52. """
  53. if len(fromstr) != len(tostr):
  54. raise ValueError, "maketrans arguments must have same length"
  55. global _idmapL
  56. if not _idmapL:
  57. _idmapL = map(None, _idmap)
  58. L = _idmapL[:]
  59. fromstr = map(ord, fromstr)
  60. for i in range(len(fromstr)):
  61. L[fromstr[i]] = tostr[i]
  62. return ''.join(L)
  63. ####################################################################
  64. import re as _re
  65. class _multimap:
  66. """Helper class for combining multiple mappings.
  67. Used by .{safe_,}substitute() to combine the mapping and keyword
  68. arguments.
  69. """
  70. def __init__(self, primary, secondary):
  71. self._primary = primary
  72. self._secondary = secondary
  73. def __getitem__(self, key):
  74. try:
  75. return self._primary[key]
  76. except KeyError:
  77. return self._secondary[key]
  78. class _TemplateMetaclass(type):
  79. pattern = r"""
  80. %(delim)s(?:
  81. (?P<escaped>%(delim)s) | # Escape sequence of two delimiters
  82. (?P<named>%(id)s) | # delimiter and a Python identifier
  83. {(?P<braced>%(id)s)} | # delimiter and a braced identifier
  84. (?P<invalid>) # Other ill-formed delimiter exprs
  85. )
  86. """
  87. def __init__(cls, name, bases, dct):
  88. super(_TemplateMetaclass, cls).__init__(name, bases, dct)
  89. if 'pattern' in dct:
  90. pattern = cls.pattern
  91. else:
  92. pattern = _TemplateMetaclass.pattern % {
  93. 'delim' : _re.escape(cls.delimiter),
  94. 'id' : cls.idpattern,
  95. }
  96. cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
  97. class Template:
  98. """A string class for supporting $-substitutions."""
  99. __metaclass__ = _TemplateMetaclass
  100. delimiter = '$'
  101. idpattern = r'[_a-z][_a-z0-9]*'
  102. def __init__(self, template):
  103. self.template = template
  104. # Search for $$, $identifier, ${identifier}, and any bare $'s
  105. def _invalid(self, mo):
  106. i = mo.start('invalid')
  107. lines = self.template[:i].splitlines(True)
  108. if not lines:
  109. colno = 1
  110. lineno = 1
  111. else:
  112. colno = i - len(''.join(lines[:-1]))
  113. lineno = len(lines)
  114. raise ValueError('Invalid placeholder in string: line %d, col %d' %
  115. (lineno, colno))
  116. def substitute(self, *args, **kws):
  117. if len(args) > 1:
  118. raise TypeError('Too many positional arguments')
  119. if not args:
  120. mapping = kws
  121. elif kws:
  122. mapping = _multimap(kws, args[0])
  123. else:
  124. mapping = args[0]
  125. # Helper function for .sub()
  126. def convert(mo):
  127. # Check the most common path first.
  128. named = mo.group('named') or mo.group('braced')
  129. if named is not None:
  130. val = mapping[named]
  131. # We use this idiom instead of str() because the latter will
  132. # fail if val is a Unicode containing non-ASCII characters.
  133. return '%s' % (val,)
  134. if mo.group('escaped') is not None:
  135. return self.delimiter
  136. if mo.group('invalid') is not None:
  137. self._invalid(mo)
  138. raise ValueError('Unrecognized named group in pattern',
  139. self.pattern)
  140. return self.pattern.sub(convert, self.template)
  141. def safe_substitute(self, *args, **kws):
  142. if len(args) > 1:
  143. raise TypeError('Too many positional arguments')
  144. if not args:
  145. mapping = kws
  146. elif kws:
  147. mapping = _multimap(kws, args[0])
  148. else:
  149. mapping = args[0]
  150. # Helper function for .sub()
  151. def convert(mo):
  152. named = mo.group('named')
  153. if named is not None:
  154. try:
  155. # We use this idiom instead of str() because the latter
  156. # will fail if val is a Unicode containing non-ASCII
  157. return '%s' % (mapping[named],)
  158. except KeyError:
  159. return self.delimiter + named
  160. braced = mo.group('braced')
  161. if braced is not None:
  162. try:
  163. return '%s' % (mapping[braced],)
  164. except KeyError:
  165. return self.delimiter + '{' + braced + '}'
  166. if mo.group('escaped') is not None:
  167. return self.delimiter
  168. if mo.group('invalid') is not None:
  169. return self.delimiter
  170. raise ValueError('Unrecognized named group in pattern',
  171. self.pattern)
  172. return self.pattern.sub(convert, self.template)
  173. ####################################################################
  174. # NOTE: Everything below here is deprecated. Use string methods instead.
  175. # This stuff will go away in Python 3.0.
  176. # Backward compatible names for exceptions
  177. index_error = ValueError
  178. atoi_error = ValueError
  179. atof_error = ValueError
  180. atol_error = ValueError
  181. # convert UPPER CASE letters to lower case
  182. def lower(s):
  183. """lower(s) -> string
  184. Return a copy of the string s converted to lowercase.
  185. """
  186. return s.lower()
  187. # Convert lower case letters to UPPER CASE
  188. def upper(s):
  189. """upper(s) -> string
  190. Return a copy of the string s converted to uppercase.
  191. """
  192. return s.upper()
  193. # Swap lower case letters and UPPER CASE
  194. def swapcase(s):
  195. """swapcase(s) -> string
  196. Return a copy of the string s with upper case characters
  197. converted to lowercase and vice versa.
  198. """
  199. return s.swapcase()
  200. # Strip leading and trailing tabs and spaces
  201. def strip(s, chars=None):
  202. """strip(s [,chars]) -> string
  203. Return a copy of the string s with leading and trailing
  204. whitespace removed.
  205. If chars is given and not None, remove characters in chars instead.
  206. If chars is unicode, S will be converted to unicode before stripping.
  207. """
  208. return s.strip(chars)
  209. # Strip leading tabs and spaces
  210. def lstrip(s, chars=None):
  211. """lstrip(s [,chars]) -> string
  212. Return a copy of the string s with leading whitespace removed.
  213. If chars is given and not None, remove characters in chars instead.
  214. """
  215. return s.lstrip(chars)
  216. # Strip trailing tabs and spaces
  217. def rstrip(s, chars=None):
  218. """rstrip(s [,chars]) -> string
  219. Return a copy of the string s with trailing whitespace removed.
  220. If chars is given and not None, remove characters in chars instead.
  221. """
  222. return s.rstrip(chars)
  223. # Split a string into a list of space/tab-separated words
  224. def split(s, sep=None, maxsplit=-1):
  225. """split(s [,sep [,maxsplit]]) -> list of strings
  226. Return a list of the words in the string s, using sep as the
  227. delimiter string. If maxsplit is given, splits at no more than
  228. maxsplit places (resulting in at most maxsplit+1 words). If sep
  229. is not specified or is None, any whitespace string is a separator.
  230. (split and splitfields are synonymous)
  231. """
  232. return s.split(sep, maxsplit)
  233. splitfields = split
  234. # Split a string into a list of space/tab-separated words
  235. def rsplit(s, sep=None, maxsplit=-1):
  236. """rsplit(s [,sep [,maxsplit]]) -> list of strings
  237. Return a list of the words in the string s, using sep as the
  238. delimiter string, starting at the end of the string and working
  239. to the front. If maxsplit is given, at most maxsplit splits are
  240. done. If sep is not specified or is None, any whitespace string
  241. is a separator.
  242. """
  243. return s.rsplit(sep, maxsplit)
  244. # Join fields with optional separator
  245. def join(words, sep = ' '):
  246. """join(list [,sep]) -> string
  247. Return a string composed of the words in list, with
  248. intervening occurrences of sep. The default separator is a
  249. single space.
  250. (joinfields and join are synonymous)
  251. """
  252. return sep.join(words)
  253. joinfields = join
  254. # Find substring, raise exception if not found
  255. def index(s, *args):
  256. """index(s, sub [,start [,end]]) -> int
  257. Like find but raises ValueError when the substring is not found.
  258. """
  259. return s.index(*args)
  260. # Find last substring, raise exception if not found
  261. def rindex(s, *args):
  262. """rindex(s, sub [,start [,end]]) -> int
  263. Like rfind but raises ValueError when the substring is not found.
  264. """
  265. return s.rindex(*args)
  266. # Count non-overlapping occurrences of substring
  267. def count(s, *args):
  268. """count(s, sub[, start[,end]]) -> int
  269. Return the number of occurrences of substring sub in string
  270. s[start:end]. Optional arguments start and end are
  271. interpreted as in slice notation.
  272. """
  273. return s.count(*args)
  274. # Find substring, return -1 if not found
  275. def find(s, *args):
  276. """find(s, sub [,start [,end]]) -> in
  277. Return the lowest index in s where substring sub is found,
  278. such that sub is contained within s[start,end]. Optional
  279. arguments start and end are interpreted as in slice notation.
  280. Return -1 on failure.
  281. """
  282. return s.find(*args)
  283. # Find last substring, return -1 if not found
  284. def rfind(s, *args):
  285. """rfind(s, sub [,start [,end]]) -> int
  286. Return the highest index in s where substring sub is found,
  287. such that sub is contained within s[start,end]. Optional
  288. arguments start and end are interpreted as in slice notation.
  289. Return -1 on failure.
  290. """
  291. return s.rfind(*args)
  292. # for a bit of speed
  293. _float = float
  294. _int = int
  295. _long = long
  296. # Convert string to float
  297. def atof(s):
  298. """atof(s) -> float
  299. Return the floating point number represented by the string s.
  300. """
  301. return _float(s)
  302. # Convert string to integer
  303. def atoi(s , base=10):
  304. """atoi(s [,base]) -> int
  305. Return the integer represented by the string s in the given
  306. base, which defaults to 10. The string s must consist of one
  307. or more digits, possibly preceded by a sign. If base is 0, it
  308. is chosen from the leading characters of s, 0 for octal, 0x or
  309. 0X for hexadecimal. If base is 16, a preceding 0x or 0X is
  310. accepted.
  311. """
  312. return _int(s, base)
  313. # Convert string to long integer
  314. def atol(s, base=10):
  315. """atol(s [,base]) -> long
  316. Return the long integer represented by the string s in the
  317. given base, which defaults to 10. The string s must consist
  318. of one or more digits, possibly preceded by a sign. If base
  319. is 0, it is chosen from the leading characters of s, 0 for
  320. octal, 0x or 0X for hexadecimal. If base is 16, a preceding
  321. 0x or 0X is accepted. A trailing L or l is not accepted,
  322. unless base is 0.
  323. """
  324. return _long(s, base)
  325. # Left-justify a string
  326. def ljust(s, width, *args):
  327. """ljust(s, width[, fillchar]) -> string
  328. Return a left-justified version of s, in a field of the
  329. specified width, padded with spaces as needed. The string is
  330. never truncated. If specified the fillchar is used instead of spaces.
  331. """
  332. return s.ljust(width, *args)
  333. # Right-justify a string
  334. def rjust(s, width, *args):
  335. """rjust(s, width[, fillchar]) -> string
  336. Return a right-justified version of s, in a field of the
  337. specified width, padded with spaces as needed. The string is
  338. never truncated. If specified the fillchar is used instead of spaces.
  339. """
  340. return s.rjust(width, *args)
  341. # Center a string
  342. def center(s, width, *args):
  343. """center(s, width[, fillchar]) -> string
  344. Return a center version of s, in a field of the specified
  345. width. padded with spaces as needed. The string is never
  346. truncated. If specified the fillchar is used instead of spaces.
  347. """
  348. return s.center(width, *args)
  349. # Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
  350. # Decadent feature: the argument may be a string or a number
  351. # (Use of this is deprecated; it should be a string as with ljust c.s.)
  352. def zfill(x, width):
  353. """zfill(x, width) -> string
  354. Pad a numeric string x with zeros on the left, to fill a field
  355. of the specified width. The string x is never truncated.
  356. """
  357. if not isinstance(x, basestring):
  358. x = repr(x)
  359. return x.zfill(width)
  360. # Expand tabs in a string.
  361. # Doesn't take non-printing chars into account, but does understand \n.
  362. def expandtabs(s, tabsize=8):
  363. """expandtabs(s [,tabsize]) -> string
  364. Return a copy of the string s with all tab characters replaced
  365. by the appropriate number of spaces, depending on the current
  366. column, and the tabsize (default 8).
  367. """
  368. return s.expandtabs(tabsize)
  369. # Character translation through look-up table.
  370. def translate(s, table, deletions=""):
  371. """translate(s,table [,deletions]) -> string
  372. Return a copy of the string s, where all characters occurring
  373. in the optional argument deletions are removed, and the
  374. remaining characters have been mapped through the given
  375. translation table, which must be a string of length 256. The
  376. deletions argument is not allowed for Unicode strings.
  377. """
  378. if deletions:
  379. return s.translate(table, deletions)
  380. else:
  381. # Add s[:0] so that if s is Unicode and table is an 8-bit string,
  382. # table is converted to Unicode. This means that table *cannot*
  383. # be a dictionary -- for that feature, use u.translate() directly.
  384. return s.translate(table + s[:0])
  385. # Capitalize a string, e.g. "aBc dEf" -> "Abc def".
  386. def capitalize(s):
  387. """capitalize(s) -> string
  388. Return a copy of the string s with only its first character
  389. capitalized.
  390. """
  391. return s.capitalize()
  392. # Substring replacement (global)
  393. def replace(s, old, new, maxsplit=-1):
  394. """replace (str, old, new[, maxsplit]) -> string
  395. Return a copy of string str with all occurrences of substring
  396. old replaced by new. If the optional argument maxsplit is
  397. given, only the first maxsplit occurrences are replaced.
  398. """
  399. return s.replace(old, new, maxsplit)
  400. # Try importing optional built-in module "strop" -- if it exists,
  401. # it redefines some string operations that are 100-1000 times faster.
  402. # It also defines values for whitespace, lowercase and uppercase
  403. # that match <ctype.h>'s definitions.
  404. try:
  405. from strop import maketrans, lowercase, uppercase, whitespace
  406. letters = lowercase + uppercase
  407. except ImportError:
  408. pass # Use the original versions