How can I print a string using .format(), and print literal curly brackets around my replaced string [duplicate]
Asked Answered
M

1

14

Possible Duplicate:
How can I print a literal “{}” characters in python string and also use .format on it?

Basically, I want to use .format(), like this:

my_string = '{{0}:{1}}'.format('hello', 'bonjour')

And have it match:

my_string = '{hello:bonjour}' #this is a string with literal curly brackets

However, the first piece of code gives me an error.

The curly brackets are important, because I'm using Python to communicate with a piece of software via text-based commands. I have no control over what kind of formatting the fosoftware expects, so it's crucial that I sort out all the formatting on my end. It uses curly brackets around strings to ensure that spaces in the strings are interpreted as single strings, rather than multiple arguments — much like you normally do with quotation marks in file paths, for example.

I'm currently using the older method:

my_string = '{%s:%s}' % ('hello', 'bonjour')

Which certainly works, but .format() seems easier to read, and when I'm sending commands with five or more variables all in one string, then readability becomes a significant issue.

Thanks!

Mystagogue answered 30/11, 2011 at 23:56 Comment(2)
Use "{{{0}:{1}}}" (double {{) #5466951Marenmarena
Yep, duplicate of that question.Beaudry
U
29

Here is the new style:

>>> '{{{0}:{1}}}'.format('hello', 'bonjour')
'{hello:bonjour}'

But I thinking escaping is somewhat hard to read, so I prefer to switch back to the older style to avoid escaping:

>>> '{%s:%s}' % ('hello', 'bonjour')
'{hello:bonjour}'
Unveiling answered 1/12, 2011 at 0:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.