String equivalent using variables - Python 3.x

Asked

Viewed 56 times

1

What would be the string equivalent :

values = """
  {
   "exchange_code": "PLNX",
   "exchange_market": "BTC/USDT"
  }
"""

Which the result is :

'\n { n "exchange_code": "PLNX", n "exchange_market": "BTC/USDT" n } n'

entering "PLNX" and "BTC/USDT" as variables, I’m trying some variations like the below but I can’t replicate the above result :

def equi_string(exchange,market):
  values = """
    {
     "exchange_code": """+exchange+""",
     "exchange_market": """+market+"""
    }
  """
  return values

'\n { n "exchange_code": PLNX, n "exchange_market": BTC/USDT n } n '

This for example is missing "" in PLNX and BTC/USDT

How do I make the string return exactly the first example ?

  • Try using json. https://docs.python.org/3/library/json.html. Probably a string in json format

1 answer

0

If you just want to create the string in this format, try using the " character to escape the quotes:

def equi_string(exchange,market):
  values = """
    {
     "exchange_code": \""""+exchange+"""\",
     "exchange_market": \""""+market+"""\"
    }
  """
  return values

Another option is to use the format, you just need to escape the keys "{" and "}":

def equi_string(exchange,market):
   values = """
     {{
      "exchange_code": "{}",
      "exchange_market": "{}"
     }}
   """
   return values.format(exchange,market)

But if you need to create more objects in this same format more complex than this, I recommend using JSON.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.