Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #40134
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: raw format string in string format method? |
| Date | 2013-02-28 16:41 +0100 |
| Organization | None |
| References | <512f6585$0$3108$ba620e4c@news.skynet.be> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2648.1362066115.2939.python-list@python.org> (permalink) |
Helmut Jarausch wrote:
> I'd like to print a string with the string format method which uses
> {0}, ...
>
> Unfortunately, the string contains TeX commands which use lots of
> braces. Therefore I would have to double all these braces just for the
> format method which makes the string hardly readable.
>
> Is there anything like a "raw" format string and any other means
> to circumvent this?
>
> Many thanks for a hint,
> Helmut.
While percent-formatting is probably the way to go here is a hack to replace
the braces with custom characters:
import string
class SwapFormatter(string.Formatter):
custom = "<>"
braces = "{}"
swap = {ord(p): q for p, q in zip(custom + braces, braces + custom)}
def format(self, format_string, *args, **kw):
format_string = format_string.translate(self.swap)
return super().format(format_string, *args, **kw)
def parse(self, format_string):
return ((t[0].translate(self.swap),) + t[1:]
for t in super().parse(format_string))
myformat = SwapFormatter().format
print(myformat("<< {} {{<0>}} <2> {<foo>} <1:<width>> >>",
"alpha", 42, "gamma", foo="delta", width=5))
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
raw format string in string format method? Helmut Jarausch <jarausch@skynet.be> - 2013-02-28 14:11 +0000
Re: raw format string in string format method? Chris Angelico <rosuav@gmail.com> - 2013-03-01 01:22 +1100
Re: raw format string in string format method? Helmut Jarausch <jarausch@skynet.be> - 2013-02-28 14:42 +0000
Re: raw format string in string format method? Chris Angelico <rosuav@gmail.com> - 2013-03-01 02:09 +1100
Re: raw format string in string format method? Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-28 15:27 -0800
Re: raw format string in string format method? Chris Angelico <rosuav@gmail.com> - 2013-03-01 15:29 +1100
Re: raw format string in string format method? Mark Lawrence <breamoreboy@yahoo.co.uk> - 2013-03-01 00:00 +0000
Re: raw format string in string format method? Peter Otten <__peter__@web.de> - 2013-02-28 16:41 +0100
Re: raw format string in string format method? Rick Johnson <rantingrickjohnson@gmail.com> - 2013-02-28 15:06 -0800
csiph-web