0

In Ruby, you can do something like:

a = 4
b = 5
match = {}
match["#{a}-#{b}"] = 0

Then, if i say:

match["4-5"]

The result is 0.

Can I do something similar in a python dictionary? I can't seem to get string formatting to work with a dictionary.

EDIT:

With f-strings in Python 3+, one can now do something like:

match[f"{a}-{b}"] = 0
dreftymac
  • 31,404
  • 26
  • 119
  • 182
ab15
  • 353
  • 1
  • 2
  • 11

1 Answers1

0

Problem

  • How to do ruby-style string variable placeholders in python.

Solution

  • Python has numerous options for doing string variable interpolation
  • Among them, a couple prominent approaches:
    • str.format in python version 2.6 and above
    • f-strings in python version 3.6 and above

Example

  import pprint
  ## using python str.format
  match     = {}
  a = 4
  b = 5
  match["{a}-{b}".format(a=a,b=b)] = 0
  pprint.pprint(match)
  pass

  ## result
  {'4-5': 0}      

See also

dreftymac
  • 31,404
  • 26
  • 119
  • 182