Inserting values into strings in Python

Viewed 79

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.

4 Answers

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.

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\"}"

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

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.

Related