Received: by 10.180.104.170 with SMTP id gf10mr3722490wib.3.1353486512920; Wed, 21 Nov 2012 00:28:32 -0800 (PST) Path: ha8ni3644wib.1!nntp.google.com!feeder2.cambriumusenet.nl!feed.tweaknews.nl!216.40.29.245.MISMATCH!novia!border4.nntp.dca.giganews.com!border2.nntp.dca.giganews.com!nntp.giganews.com!news.glorb.com!news.astraweb.com!border6.newsrouter.astraweb.com!not-for-mail From: Steven D'Aprano Subject: Re: Error messages from format() Newsgroups: comp.lang.python References: MIME-Version: 1.0 Date: 13 Nov 2012 18:38:25 GMT Lines: 64 Message-ID: <50a293a0$0$29999$c3e8da3$5496439d@news.astraweb.com> Organization: Unlimited download news at news.astraweb.com NNTP-Posting-Host: 4a95115a.news.astraweb.com X-Trace: DXC=6_NEV\=i17HU8fT?_VL23KL?0kYOcDh@JN7:H2`MmAUCUD6cPA?_dmM]G;2>V^?kWC2Of6BS7?ncJ^h]M7h=c0AD>h=3m[9[RUN Bytes: 2691 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On Tue, 13 Nov 2012 10:08:59 -0500, Colin J. Williams wrote: > Is there some way to get more informative error messages from the > builtin format? Yes -- post a feature request on the Python bug tracker, then wait until Python 3.4 comes out in about 16 months. :( > Most messages are such as: > Traceback (most recent call last): > File "", line 1, in > ValueError: Invalid conversion specification > > This example doesn't point to the first invalid case. Better error messages would be valuable. > [Dbg]>>> format((25, 31),'{0^9o} a(1:9x}') > Traceback (most recent call last): > File "", line 1, in > ValueError: Invalid conversion specification I see at least three problems. (1) The first brace substitution is missing the colon between the argument selector "0" and the format spec "^9o": should be "{0:^9o}". (2) The second format string has an opening round bracket instead of brace: (1:9x} (3) But you are confusing the str.format method with the format function. The format function doesn't take brace substitutions! The string format method takes a template including brace substitutions, plus multiple "objects to be substituted", like this: py> '{0:^9o} a{1:9x}'.format(25, 31) ' 31 a 1f' In this case, the template '{0:^9o} a{1:9x}' requires two arguments since it has two substitutions, {0} and {1}. Each substitution has a format spec following the colon: {0:^9o} and {1:9x} But the format function only takes a single "object to be substituted", and so doesn't take a brace substitution. Instead, it just takes the format spec part: py> format(25, '^9o') ' 31 ' py> format(31, '^9o') ' 37 ' format will not split a tuple into multiple arguments for you, since the tuple is considered a single object. -- Steven