Source code for uw.stringtools

"""String-handling utilities.

Contains a procedure to facilitate multiple string substitutions, and a
slight enhancement of the Python-standard :meth:`str.strip`.
"""

import re

[docs]def multiReplace (changes): r"""Create a procedure to perform multiple string substitutions. :param dict changes: dictionary of substitutions; keys will be replaced by values. The returned procedure expects a string and returns a string. The result string consists of the input string with the specified substitutions performed. The changes are a dictionary of find/replace values. The "find" values (dictionary keys) are simultaneously found and each occurrence is replaced by the corresponding "replace" value (dictionary value). Works by constructing a regular expression corresponding to the alternation of the keys of the dictionary. In the event that "find" strings overlap, behaviour is determined by the :mod:`re` library. A special case allows for correct handling of the "empty dictionary" case of no replacements. """ if len (changes): pattern = re.compile ('|'.join ([re.escape (key) for key in changes.keys ()])) else: # The empty alternation is the "match no strings" RE, which is not # the same as the RE represented by the empty string. It is # impossible to match a character followed by the beginning of the # string, so this works. pattern = re.compile (r".\A") def handleMatch (match): return changes[match.group (0)] return lambda string: re.sub (pattern, handleMatch, string)
[docs]def strip_string (s): """Trim whitespace off a string, and recognize empty strings. :param str s: the string to strip. This is intended for processing text form fields. It strips whitespace off the ends of the string; if an empty string is all that remains, None is returned. None is also returned if s is None. """ return None if s is None else s.strip () or None