Using '{' as a string in the format method python - python

I want to be able to print something like such "{x}" using the format method, but the nature of the curly braces is messing me up.
I tried
'{{}}'.format(x)
however that returned a value error. Is there a way to tell python that the curly brace is meant to be used as a string rather than an argument for the format?

{{ is converted into {by format, so use this:
'{{{}}}'.format(x)
(note the three braces)
However, in this case, I would use the older C-style format string:
'{%s}' % x
It is a lot clearer.

Related

Getting Error in python SyntaxError: f-string: expressions nested too deeply

I am getting this error, i also need to pass variable in that string but it is giving this error for the following code:
for i in range (0,4):
str =f'{"requests":[{"indexName":"New_Telemart","params":"query=Mobiles&maxValuesPerFacet=10&page="{i}"&highlightPreTag=__ais-highlight__&highlightPostTag=__%2Fais-highlight__&facets=%5B%22brand_name%22%2C%22categories%22%2C%22sale_price%22%2C%22total_rating_average%22%2C%22express_delivery%22%5D&tagFilters=&facetFilters=%5B%5B%22categories%3ASmartphones%22%2C%22categories%3AMobile%20%26%20Tablets%22%5D%5D"}, {"indexName":"New_Telemart","params":"query=Mobiles&maxValuesPerFacet=10&page=0&highlightPreTag=__ais-highlight__&highlightPostTag=__%2Fais-highlight__&hitsPerPage=1&attributesToRetrieve=%5B%5D&attributesToHighlight=%5B%5D&attributesToSnippet=%5B%5D&tagFilters=&analytics=false&clickAnalytics=false&facets=categories"}]}'
print(str)
Error:
I believe just just need to escape the curly brackets to make this work:
f'{{"requests":[{{"indexName":"New_Telemart","params":"query=Mobiles&maxValuesPerFacet=10&page="{i}"&highlightPreTag=__ais-highlight__&highlightPostTag=__%2Fais-highlight__&facets=%5B%22brand_name%22%2C%22categories%22%2C%22sale_price%22%2C%22total_rating_average%22%2C%22express_delivery%22%5D&tagFilters=&facetFilters=%5B%5B%22categories%3ASmartphones%22%2C%22categories%3AMobile%20%26%20Tablets%22%5D%5D"}}, {{"indexName":"New_Telemart","params":"query=Mobiles&maxValuesPerFacet=10&page=0&highlightPreTag=__ais-highlight__&highlightPostTag=__%2Fais-highlight__&hitsPerPage=1&attributesToRetrieve=%5B%5D&attributesToHighlight=%5B%5D&attributesToSnippet=%5B%5D&tagFilters=&analytics=false&clickAnalytics=false&facets=categories"}}]}}'
You can read the f-string documentation for more information
The error is caused by the fact that the string is including dictionaries. As the standard dictionary and f-string uses {}, you are indeed going too deep. You will need to escape the brackets or remove the dictionary from the string to effectively utilize the f-string.

Override {} placeholders in python string format method

I am trying to use python format method to do format my placeholder in a string.
The issue is the string contains {} internally and the string method is unable to resolve it.
my_value='v'
'{"k":"{value}"}'.format(value=my_value) # This results in error due to outside {}
# Desired Output '{"k":"v"}'
How would I resolve this ?
I can convert this to json and then substitute but I prefer if the string format can do it
You don't need to override something, you can just escape the curly brackets by doubling them, as stated in the documentation for the format string syntax:
If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.
>>> '{{"k":"{value}"}}'.format(value=my_value)
'{"k":"v"}'
This equally applies for formatted string literals if you plan on using them at some point:
>>> f'{{"k": "{my_value}"}}'
'{"k": "v"}'

Python - How can I convert a special character to the unicode representation?

In a dictionary, I have the following value with equals signal:
{"appVersion":"o0u5jeWA6TwlJacNFnjiTA=="}
To be explicit, I need to replace the = for the unicode representation '\u003d' (basically the reverse process of [json.loads()][1]). How can I set the unicode value to a variable without store the value with two scapes (\\u003d)?.
I've tryed of different ways, including the enconde/decode, repr(), unichr(61), etc, and even searching a lot, cound't find anything that does this, all the ways give me the following final result (or the original result):
'o0u5jeWA6TwlJacNFnjiTA\\u003d\\u003d'
Since now, thanks for your attention.
EDIT
When I debug the code, it gives me the value of the variable with 2 escapes. The program will get this value and use it to do the following actions, including the extra escape. I'm using this code to construct a json by the json.dumps() and the result returned is a unicode with 2 escapes.
Follow a print of the final result after the JSON construction. I need to find a way to store the value in the var with just one escape.
I don't know if make difference, but I'm doing this to a custom BURP Plugin, manipulating some selected requests.
Here is an image of my POC, getting the value of the var.
The extra backslash is not actually added, The Python interpreter uses the repr() to indicate that it's a backslash not something like \t or \n when the string containing \ gets printed:
I hope this helps:
>>> t['appVersion'] = t["appVersion"].replace('=', '\u003d')
>>> t['appVersion']
'o0u5jeWA6TwlJacNFnjiTA\\u003d\\u003d'
>>> print(t['appVersion'])
o0u5jeWA6TwlJacNFnjiTA\u003d\u003d
>>> t['appVersion'] == 'o0u5jeWA6TwlJacNFnjiTA\u003d\u003d'
True

python Variable in a string

I am trying to specify a standard binary format length from a variable but for some reason it never works. Am I doing the formatting wrong or the variable inclusion?
comp.write("{0:%ib}".format(I) % num_bits)
ValueError: Invalid conversion specification
Firstly, it's in the wrong order:
("{0:%ib}" % num_bits).format(I)
Secondly, this isn't the way to do it! Mixing up types of formatting operator implies you don't know it can be done together. You want:
"{:{}b}".format(I, num_bits)
and if you really want to do it in two steps:
"{{:{}b}}".format(num_bits).format(I)
The {{ and }} are escaped, so are transformed to single braces, after the first .format.
You're doing the interpolation the wrong way round. You'll need to resolve the %i before passing it to format. This would work:
comp.write(("{0:%ib}" % num_bits).format(I))
but is pretty horrible, you probably want to split it into two:
fmt = "{0:%ib}" % num_bits
comp.write(fmt.format(I))

Loading document as raw string in yaml with PyYAML

I want to parse yaml documents like the following
meta-info-1: val1
meta-info-2: val2
---
Plain text/markdown content!
jhaha
If I load_all this with PyYAML, I get the following
>>> list(yaml.load_all(open('index.yml')))
[{'meta-info-1': 'val1', 'meta-info-2': 'val2'}, 'Plain text/markdown content! jhaha']
What I am trying to achieve here is that the yaml file should contain two documents, and the second one is supposed to be interpreted as a single string document, more specifically any large body of text with markdown formatting. I don't want it to be parsed as YAML syntax.
In the above example, PyYAML returns the second document as a single string. But if the second document has a : character in place of the ! for instance, I get a syntax error. This is because PyYAML is parsing the stuff in that document.
Is there a way I can tell PyYAML that the second document is a just a raw string and not to parse it?
Edit: A few excellent answers there. While using quotes or the literal syntax solves the said problem, I'd like the users to be able to write the plain text without any extra cruft. Just the three -'s (or .'s) and write away a large body of plain text. Which might also include quotes too. So, I'd like to know if I can tell PyYAML to parse only one document, and give the second to me raw.
Eidt 2: So, adapting agf's idea, instead of using a try/except as the second document could be valid yaml syntax,
config_content, body_content = open(filename).read().split('\n---')
config = yaml.loads(config_content)
body = yaml.loads(body_content)
Thanks agf.
You can do
raw = open(filename).read()
docs = []
for raw_doc in raw.split('\n---'):
try:
docs.append(yaml.load(raw_doc))
except SyntaxError:
docs.append(raw_doc)
If you won't have control over the format of the original document.
From the PyYAML docs,
Double-quoted is the most powerful style and the only style that can express any scalar value. Double-quoted scalars allow escaping. Using escaping sequences \x** and \u****, you may express any ASCII or Unicode character.
So it sounds like there is no way to represent an arbitrary scalar in the parsing if it's not double quoted.
If all you want is to escape the colon character in YAML, then enclose it within single or double quotes. Also, you can try literal style for your second document which should be treated as single scalar.

Categories