Showing posts with label regex. Show all posts
Showing posts with label regex. Show all posts

Tuesday, March 15, 2011

Emacs back references in replace-regex.

From http://www.gnu.org/software/emacs/manual/html_node/emacs/Regexp-Replace.html

In replace-regexp, the newstring need not be constant: it can refer to all or part of what is matched by the regexp. ‘\&’ in newstring stands for the entire match being replaced. ‘\d’ in newstring, where d is a digit, stands for whatever matched the dth parenthesized grouping in regexp. (This is called a “back reference.”) ‘\#’ refers to the count of replacements already made in this command, as a decimal number. In the first replacement, ‘\#’ stands for ‘0’; in the second, for ‘1’; and so on. For example,

M-x replace-regexp <RET> c[ad]+r <RET> \&-safe <RET>

replaces (for example) ‘cadr’ with ‘cadr-safe’ and ‘cddr’ with ‘cddr-safe’.

Monday, June 8, 2009

TypeError: not enough arguments for format string

Got this error in some python code the other day:

TypeError: not enough arguments for format string


Essentially it means you have something like the following in your code:

"%s,%s,%s" % ('foo','bar')


Essentially it's saying there aren't enough strings to fill the placeholders. But it also means that there might be an errant % in the template string that you weren't anticipating such as:

"%s has 42% of the shares." % ('Bob')


which is annoying. A regex you can run on your code to roughly handle this is:

regex1 = re.compile('%(?![\(])')
regex2 = re.compile('%%+')
cooked_html = regex1.sub('%%', regex2.sub('%', raw_html))
I say roughly since if you're starting to run into these kinds of situations, you really need to start using a templating engine like jinja or mako. I'll switch to mako in the future.