3

I am trying to iterate over some integer values and insert them into an string which has to be in a weird format to work. The exact output (including the outer quotes) I need if the value was 64015 would be:

"param={\"zip\":\"64015\"}"

I have tried f string formatting but couldn't get it to work. It has problem with the backslashes and when I escaped them the output was not exactly like above string Hopefully, I made myself clear enough.

0

4 Answers 4

1

You would have to escape the backslash and the double quotes seperately like this:

string = '"param={\\\"zip\\\":\\\"' + str(64015) + '\\\"}"'

The result of this is:

"param={\"zip\":\"64015\"}"
Sign up to request clarification or add additional context in comments.

Comments

1

You can use alternate ways to delimit the outer string ('...', '''...''', """...""") or use str.format() or old style %-formatting syntax to get there (see f-style workaround at the end):

s = s =  'param={"zip":"' + str(64015) + '"}' 
print(s)

s =  '''param={"zip":"''' + str(64015) +'''"}''' 
print(s)

s =  """param={"zip":"64015"}"""   # not suited for variable replacement 
print(s)

s =  'param={{"zip":"{0}"}}'.format(64015)
print(s)

s =  'param={"zip":"%s"}' % 64015
print(s)

Output:

param={"zip":"64015"}
param={"zip":"64015"}
param={"zip":"64015"}
param={"zip":"64015"}

If you need any "\" in there simply drop a \\ in:

s =  '"param={\\"zip\\":\\"' + str(64015) + '\\"}"' 
print(s)

s =  '''"param={\\"zip\\":\\"''' + str(64015) +'''\\"}"''' 
print(s)


s =  '"param={{\\"zip\\":\\"{0}\\"}}"'.format(64015)
print(s)

s =  '"param={\\"zip\\":\\"%s\\"}"' % 64015
print(s)

Output:

"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"
"param={\"zip\":\"64015\"}"

The f-string workaround variant would look like so:

a = '\\"'
num = 64015
s = f'"param={{{a}zip{a}:{a}{num}{a}}}"'

and if printed also yields :

"param={\"zip\":\"64015\"}"

More on the topic can be found here: 'Custom string formatting' on python.org

6 Comments

Well done on working out the f-string version.
@Patrick Artner Thank you for your comprehensive answer. Your answer with "\" is what I need but I don't want to print the answer. "s" will be an input to another function and its value (without being printed) has to be exactly "param={\"zip\":\"64015\"}". Just to give a bit of a context "s" will be assigned to "data" in the following function: r = requests.post(url , data= "param={\"zip\":\"64015\"}", headers)
@shora - in that case a = '\\"' + s = f'"param={{{a}zip{a}:{a}{your_number}{a}}}"' should work. If I were you I would do a quick test and try if s = 'param={"zip":"64015"}' is accepted by your api as well. Although otherwise documented it could/may work.
@PatrickArtner I tested 'param={"zip":"64015"}'. Unfortunately, it doesn't work due to the way they design the API. That's why I have to go through the hassle of generating this string. Also, I have just check the value of s based on your updated string but it returns '"param={\\"zip\\":\\"your_number\\"}"' which still doesn't work because it has double backslashes instead of single. Seems that it is really hard to generate what I need!
@Shora Then you do NOT need the \ before the " - if you debug something or use an IDE with inspect functionality on breaks it sometimes it escapes " for your viewing pleasure. Surest thing is to print() the string. Send if over once with, once without and see what works. You can change a='"' (single+double+single) to generate it without \
|
1

I played around a bit with f-strings and .format() but ultimately got this to work:

foo = 90210
bar = '"param={\\"zip\\":\\"%s\\"}"' % (foo)
print(bar)

giving:

"param={\"zip\":\"90210\"}"

Hopefully someone can give you an f-string alternative. I kept running into unallowed "\" in my f-string attempts.

Comments

0

Is it only this?

a = "param={\"zip\":\"64015\"}"
b = a.split('=')
c = eval(b[1])
print(c)
print(c['zip'])

Result:

{'zip': '64015'}
64015

Please note that evaluating (eval()) strings from unknown source may be dangerous! It may run the code that you are not expecting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.