Re: raw format string in string format method?

Discussion in 'Python' started by Peter Otten, Feb 28, 2013.

  1. Peter Otten

    Peter Otten Guest

    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))
     
    Peter Otten, Feb 28, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ven
    Replies:
    6
    Views:
    530
  2. bharath
    Replies:
    4
    Views:
    3,340
    Thomas Fritsch
    Mar 16, 2007
  3. ankur
    Replies:
    1
    Views:
    12,969
    Jan =?UTF-8?B?VGhvbcOk?=
    Aug 27, 2007
  4. Chris Angelico
    Replies:
    3
    Views:
    167
    Mark Lawrence
    Mar 1, 2013
  5. Rick Johnson
    Replies:
    0
    Views:
    149
    Rick Johnson
    Feb 28, 2013
Loading...

Share This Page