PageRenderTime 57ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/string.py

https://bitbucket.org/bwesterb/pypy
Python | 642 lines | 634 code | 3 blank | 5 comment | 1 complexity | ac93b6b7b6e6d1d4bc3105662c0c854d MD5 | raw file
  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. If the optional second argument sep is absent or None,
  42. runs of whitespace characters are replaced by a single space
  43. and leading and trailing whitespace are removed, otherwise
  44. sep is used to split and join the words.
  45. """
  46. return (sep or ' ').join(x.capitalize() for x in s.split(sep))
  47. # Construct a translation string
  48. _idmapL = None
  49. def maketrans(fromstr, tostr):
  50. """maketrans(frm, to) -> string
  51. Return a translation table (a string of 256 bytes long)
  52. suitable for use in string.translate. The strings frm and to
  53. must be of the same length.
  54. """
  55. if len(fromstr) != len(tostr):
  56. raise ValueError, "maketrans arguments must have same length"
  57. global _idmapL
  58. if not _idmapL:
  59. _idmapL = list(_idmap)
  60. L = _idmapL[:]
  61. fromstr = map(ord, fromstr)
  62. for i in range(len(fromstr)):
  63. L[fromstr[i]] = tostr[i]
  64. return ''.join(L)
  65. ####################################################################
  66. import re as _re
  67. class _multimap:
  68. """Helper class for combining multiple mappings.
  69. Used by .{safe_,}substitute() to combine the mapping and keyword
  70. arguments.
  71. """
  72. def __init__(self, primary, secondary):
  73. self._primary = primary
  74. self._secondary = secondary
  75. def __getitem__(self, key):
  76. try:
  77. return self._primary[key]
  78. except KeyError:
  79. return self._secondary[key]
  80. class _TemplateMetaclass(type):
  81. pattern = r"""
  82. %(delim)s(?:
  83. (?P<escaped>%(delim)s) | # Escape sequence of two delimiters
  84. (?P<named>%(id)s) | # delimiter and a Python identifier
  85. {(?P<braced>%(id)s)} | # delimiter and a braced identifier
  86. (?P<invalid>) # Other ill-formed delimiter exprs
  87. )
  88. """
  89. def __init__(cls, name, bases, dct):
  90. super(_TemplateMetaclass, cls).__init__(name, bases, dct)
  91. if 'pattern' in dct:
  92. pattern = cls.pattern
  93. else:
  94. pattern = _TemplateMetaclass.pattern % {
  95. 'delim' : _re.escape(cls.delimiter),
  96. 'id' : cls.idpattern,
  97. }
  98. cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
  99. class Template:
  100. """A string class for supporting $-substitutions."""
  101. __metaclass__ = _TemplateMetaclass
  102. delimiter = '$'
  103. idpattern = r'[_a-z][_a-z0-9]*'
  104. def __init__(self, template):
  105. self.template = template
  106. # Search for $$, $identifier, ${identifier}, and any bare $'s
  107. def _invalid(self, mo):
  108. i = mo.start('invalid')
  109. lines = self.template[:i].splitlines(True)
  110. if not lines:
  111. colno = 1
  112. lineno = 1
  113. else:
  114. colno = i - len(''.join(lines[:-1]))
  115. lineno = len(lines)
  116. raise ValueError('Invalid placeholder in string: line %d, col %d' %
  117. (lineno, colno))
  118. def substitute(self, *args, **kws):
  119. if len(args) > 1:
  120. raise TypeError('Too many positional arguments')
  121. if not args:
  122. mapping = kws
  123. elif kws:
  124. mapping = _multimap(kws, args[0])
  125. else:
  126. mapping = args[0]
  127. # Helper function for .sub()
  128. def convert(mo):
  129. # Check the most common path first.
  130. named = mo.group('named') or mo.group('braced')
  131. if named is not None:
  132. val = mapping[named]
  133. # We use this idiom instead of str() because the latter will
  134. # fail if val is a Unicode containing non-ASCII characters.
  135. return '%s' % (val,)
  136. if mo.group('escaped') is not None:
  137. return self.delimiter
  138. if mo.group('invalid') is not None:
  139. self._invalid(mo)
  140. raise ValueError('Unrecognized named group in pattern',
  141. self.pattern)
  142. return self.pattern.sub(convert, self.template)
  143. def safe_substitute(self, *args, **kws):
  144. if len(args) > 1:
  145. raise TypeError('Too many positional arguments')
  146. if not args:
  147. mapping = kws
  148. elif kws:
  149. mapping = _multimap(kws, args[0])
  150. else:
  151. mapping = args[0]
  152. # Helper function for .sub()
  153. def convert(mo):
  154. named = mo.group('named')
  155. if named is not None:
  156. try:
  157. # We use this idiom instead of str() because the latter
  158. # will fail if val is a Unicode containing non-ASCII
  159. return '%s' % (mapping[named],)
  160. except KeyError:
  161. return self.delimiter + named
  162. braced = mo.group('braced')
  163. if braced is not None:
  164. try:
  165. return '%s' % (mapping[braced],)
  166. except KeyError:
  167. return self.delimiter + '{' + braced + '}'
  168. if mo.group('escaped') is not None:
  169. return self.delimiter
  170. if mo.group('invalid') is not None:
  171. return self.delimiter
  172. raise ValueError('Unrecognized named group in pattern',
  173. self.pattern)
  174. return self.pattern.sub(convert, self.template)
  175. ####################################################################
  176. # NOTE: Everything below here is deprecated. Use string methods instead.
  177. # This stuff will go away in Python 3.0.
  178. # Backward compatible names for exceptions
  179. index_error = ValueError
  180. atoi_error = ValueError
  181. atof_error = ValueError
  182. atol_error = ValueError
  183. # convert UPPER CASE letters to lower case
  184. def lower(s):
  185. """lower(s) -> string
  186. Return a copy of the string s converted to lowercase.
  187. """
  188. return s.lower()
  189. # Convert lower case letters to UPPER CASE
  190. def upper(s):
  191. """upper(s) -> string
  192. Return a copy of the string s converted to uppercase.
  193. """
  194. return s.upper()
  195. # Swap lower case letters and UPPER CASE
  196. def swapcase(s):
  197. """swapcase(s) -> string
  198. Return a copy of the string s with upper case characters
  199. converted to lowercase and vice versa.
  200. """
  201. return s.swapcase()
  202. # Strip leading and trailing tabs and spaces
  203. def strip(s, chars=None):
  204. """strip(s [,chars]) -> string
  205. Return a copy of the string s with leading and trailing
  206. whitespace removed.
  207. If chars is given and not None, remove characters in chars instead.
  208. If chars is unicode, S will be converted to unicode before stripping.
  209. """
  210. return s.strip(chars)
  211. # Strip leading tabs and spaces
  212. def lstrip(s, chars=None):
  213. """lstrip(s [,chars]) -> string
  214. Return a copy of the string s with leading whitespace removed.
  215. If chars is given and not None, remove characters in chars instead.
  216. """
  217. return s.lstrip(chars)
  218. # Strip trailing tabs and spaces
  219. def rstrip(s, chars=None):
  220. """rstrip(s [,chars]) -> string
  221. Return a copy of the string s with trailing whitespace removed.
  222. If chars is given and not None, remove characters in chars instead.
  223. """
  224. return s.rstrip(chars)
  225. # Split a string into a list of space/tab-separated words
  226. def split(s, sep=None, maxsplit=-1):
  227. """split(s [,sep [,maxsplit]]) -> list of strings
  228. Return a list of the words in the string s, using sep as the
  229. delimiter string. If maxsplit is given, splits at no more than
  230. maxsplit places (resulting in at most maxsplit+1 words). If sep
  231. is not specified or is None, any whitespace string is a separator.
  232. (split and splitfields are synonymous)
  233. """
  234. return s.split(sep, maxsplit)
  235. splitfields = split
  236. # Split a string into a list of space/tab-separated words
  237. def rsplit(s, sep=None, maxsplit=-1):
  238. """rsplit(s [,sep [,maxsplit]]) -> list of strings
  239. Return a list of the words in the string s, using sep as the
  240. delimiter string, starting at the end of the string and working
  241. to the front. If maxsplit is given, at most maxsplit splits are
  242. done. If sep is not specified or is None, any whitespace string
  243. is a separator.
  244. """
  245. return s.rsplit(sep, maxsplit)
  246. # Join fields with optional separator
  247. def join(words, sep = ' '):
  248. """join(list [,sep]) -> string
  249. Return a string composed of the words in list, with
  250. intervening occurrences of sep. The default separator is a
  251. single space.
  252. (joinfields and join are synonymous)
  253. """
  254. return sep.join(words)
  255. joinfields = join
  256. # Find substring, raise exception if not found
  257. def index(s, *args):
  258. """index(s, sub [,start [,end]]) -> int
  259. Like find but raises ValueError when the substring is not found.
  260. """
  261. return s.index(*args)
  262. # Find last substring, raise exception if not found
  263. def rindex(s, *args):
  264. """rindex(s, sub [,start [,end]]) -> int
  265. Like rfind but raises ValueError when the substring is not found.
  266. """
  267. return s.rindex(*args)
  268. # Count non-overlapping occurrences of substring
  269. def count(s, *args):
  270. """count(s, sub[, start[,end]]) -> int
  271. Return the number of occurrences of substring sub in string
  272. s[start:end]. Optional arguments start and end are
  273. interpreted as in slice notation.
  274. """
  275. return s.count(*args)
  276. # Find substring, return -1 if not found
  277. def find(s, *args):
  278. """find(s, sub [,start [,end]]) -> in
  279. Return the lowest index in s where substring sub is found,
  280. such that sub is contained within s[start,end]. Optional
  281. arguments start and end are interpreted as in slice notation.
  282. Return -1 on failure.
  283. """
  284. return s.find(*args)
  285. # Find last substring, return -1 if not found
  286. def rfind(s, *args):
  287. """rfind(s, sub [,start [,end]]) -> int
  288. Return the highest index in s where substring sub is found,
  289. such that sub is contained within s[start,end]. Optional
  290. arguments start and end are interpreted as in slice notation.
  291. Return -1 on failure.
  292. """
  293. return s.rfind(*args)
  294. # for a bit of speed
  295. _float = float
  296. _int = int
  297. _long = long
  298. # Convert string to float
  299. def atof(s):
  300. """atof(s) -> float
  301. Return the floating point number represented by the string s.
  302. """
  303. return _float(s)
  304. # Convert string to integer
  305. def atoi(s , base=10):
  306. """atoi(s [,base]) -> int
  307. Return the integer represented by the string s in the given
  308. base, which defaults to 10. The string s must consist of one
  309. or more digits, possibly preceded by a sign. If base is 0, it
  310. is chosen from the leading characters of s, 0 for octal, 0x or
  311. 0X for hexadecimal. If base is 16, a preceding 0x or 0X is
  312. accepted.
  313. """
  314. return _int(s, base)
  315. # Convert string to long integer
  316. def atol(s, base=10):
  317. """atol(s [,base]) -> long
  318. Return the long integer represented by the string s in the
  319. given base, which defaults to 10. The string s must consist
  320. of one or more digits, possibly preceded by a sign. If base
  321. is 0, it is chosen from the leading characters of s, 0 for
  322. octal, 0x or 0X for hexadecimal. If base is 16, a preceding
  323. 0x or 0X is accepted. A trailing L or l is not accepted,
  324. unless base is 0.
  325. """
  326. return _long(s, base)
  327. # Left-justify a string
  328. def ljust(s, width, *args):
  329. """ljust(s, width[, fillchar]) -> string
  330. Return a left-justified version of s, in a field of the
  331. specified width, padded with spaces as needed. The string is
  332. never truncated. If specified the fillchar is used instead of spaces.
  333. """
  334. return s.ljust(width, *args)
  335. # Right-justify a string
  336. def rjust(s, width, *args):
  337. """rjust(s, width[, fillchar]) -> string
  338. Return a right-justified version of s, in a field of the
  339. specified width, padded with spaces as needed. The string is
  340. never truncated. If specified the fillchar is used instead of spaces.
  341. """
  342. return s.rjust(width, *args)
  343. # Center a string
  344. def center(s, width, *args):
  345. """center(s, width[, fillchar]) -> string
  346. Return a center version of s, in a field of the specified
  347. width. padded with spaces as needed. The string is never
  348. truncated. If specified the fillchar is used instead of spaces.
  349. """
  350. return s.center(width, *args)
  351. # Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
  352. # Decadent feature: the argument may be a string or a number
  353. # (Use of this is deprecated; it should be a string as with ljust c.s.)
  354. def zfill(x, width):
  355. """zfill(x, width) -> string
  356. Pad a numeric string x with zeros on the left, to fill a field
  357. of the specified width. The string x is never truncated.
  358. """
  359. if not isinstance(x, basestring):
  360. x = repr(x)
  361. return x.zfill(width)
  362. # Expand tabs in a string.
  363. # Doesn't take non-printing chars into account, but does understand \n.
  364. def expandtabs(s, tabsize=8):
  365. """expandtabs(s [,tabsize]) -> string
  366. Return a copy of the string s with all tab characters replaced
  367. by the appropriate number of spaces, depending on the current
  368. column, and the tabsize (default 8).
  369. """
  370. return s.expandtabs(tabsize)
  371. # Character translation through look-up table.
  372. def translate(s, table, deletions=""):
  373. """translate(s,table [,deletions]) -> string
  374. Return a copy of the string s, where all characters occurring
  375. in the optional argument deletions are removed, and the
  376. remaining characters have been mapped through the given
  377. translation table, which must be a string of length 256. The
  378. deletions argument is not allowed for Unicode strings.
  379. """
  380. if deletions or table is None:
  381. return s.translate(table, deletions)
  382. else:
  383. # Add s[:0] so that if s is Unicode and table is an 8-bit string,
  384. # table is converted to Unicode. This means that table *cannot*
  385. # be a dictionary -- for that feature, use u.translate() directly.
  386. return s.translate(table + s[:0])
  387. # Capitalize a string, e.g. "aBc dEf" -> "Abc def".
  388. def capitalize(s):
  389. """capitalize(s) -> string
  390. Return a copy of the string s with only its first character
  391. capitalized.
  392. """
  393. return s.capitalize()
  394. # Substring replacement (global)
  395. def replace(s, old, new, maxreplace=-1):
  396. """replace (str, old, new[, maxreplace]) -> string
  397. Return a copy of string str with all occurrences of substring
  398. old replaced by new. If the optional argument maxreplace is
  399. given, only the first maxreplace occurrences are replaced.
  400. """
  401. return s.replace(old, new, maxreplace)
  402. # Try importing optional built-in module "strop" -- if it exists,
  403. # it redefines some string operations that are 100-1000 times faster.
  404. # It also defines values for whitespace, lowercase and uppercase
  405. # that match <ctype.h>'s definitions.
  406. try:
  407. from strop import maketrans, lowercase, uppercase, whitespace
  408. letters = lowercase + uppercase
  409. except ImportError:
  410. pass # Use the original versions
  411. ########################################################################
  412. # the Formatter class
  413. # see PEP 3101 for details and purpose of this class
  414. # The hard parts are reused from the C implementation. They're exposed as "_"
  415. # prefixed methods of str and unicode.
  416. # The overall parser is implemented in str._formatter_parser.
  417. # The field name parser is implemented in str._formatter_field_name_split
  418. class Formatter(object):
  419. def format(self, format_string, *args, **kwargs):
  420. return self.vformat(format_string, args, kwargs)
  421. def vformat(self, format_string, args, kwargs):
  422. used_args = set()
  423. result = self._vformat(format_string, args, kwargs, used_args, 2)
  424. self.check_unused_args(used_args, args, kwargs)
  425. return result
  426. def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):
  427. if recursion_depth < 0:
  428. raise ValueError('Max string recursion exceeded')
  429. result = []
  430. for literal_text, field_name, format_spec, conversion in \
  431. self.parse(format_string):
  432. # output the literal text
  433. if literal_text:
  434. result.append(literal_text)
  435. # if there's a field, output it
  436. if field_name is not None:
  437. # this is some markup, find the object and do
  438. # the formatting
  439. # given the field_name, find the object it references
  440. # and the argument it came from
  441. obj, arg_used = self.get_field(field_name, args, kwargs)
  442. used_args.add(arg_used)
  443. # do any conversion on the resulting object
  444. obj = self.convert_field(obj, conversion)
  445. # expand the format spec, if needed
  446. format_spec = self._vformat(format_spec, args, kwargs,
  447. used_args, recursion_depth-1)
  448. # format the object and append to the result
  449. result.append(self.format_field(obj, format_spec))
  450. return ''.join(result)
  451. def get_value(self, key, args, kwargs):
  452. if isinstance(key, (int, long)):
  453. return args[key]
  454. else:
  455. return kwargs[key]
  456. def check_unused_args(self, used_args, args, kwargs):
  457. pass
  458. def format_field(self, value, format_spec):
  459. return format(value, format_spec)
  460. def convert_field(self, value, conversion):
  461. # do any conversion on the resulting object
  462. if conversion == 'r':
  463. return repr(value)
  464. elif conversion == 's':
  465. return str(value)
  466. elif conversion is None:
  467. return value
  468. raise ValueError("Unknown conversion specifier {0!s}".format(conversion))
  469. # returns an iterable that contains tuples of the form:
  470. # (literal_text, field_name, format_spec, conversion)
  471. # literal_text can be zero length
  472. # field_name can be None, in which case there's no
  473. # object to format and output
  474. # if field_name is not None, it is looked up, formatted
  475. # with format_spec and conversion and then used
  476. def parse(self, format_string):
  477. return format_string._formatter_parser()
  478. # given a field_name, find the object it references.
  479. # field_name: the field being looked up, e.g. "0.name"
  480. # or "lookup[3]"
  481. # used_args: a set of which args have been used
  482. # args, kwargs: as passed in to vformat
  483. def get_field(self, field_name, args, kwargs):
  484. first, rest = field_name._formatter_field_name_split()
  485. obj = self.get_value(first, args, kwargs)
  486. # loop through the rest of the field_name, doing
  487. # getattr or getitem as needed
  488. for is_attr, i in rest:
  489. if is_attr:
  490. obj = getattr(obj, i)
  491. else:
  492. obj = obj[i]
  493. return obj, first