1

Is it possible to inject variable values into strings without knowing the order?
I'm familiar with

"% world" % "Hello"

syntax, but is there anything comparable to

string = "Order id %{order.id}, price: %price" % (price, order)

I'm asking because I'd like to have a list of strings with inconsistant use of variables, and their placement, and I want to substitute them all inside of a function.

Mikhail
  • 8,692
  • 8
  • 56
  • 82
  • There may be a dupe of this lying around somewhere, but the linked dupe doesn't consider the case of attribute access within the string. `"{order.id}".format(order=...)` – mgilson Mar 01 '13 at 02:01
  • You're right; it's somewhat similar, and the answer kinda covers it, but I never ran upon that question because of the various ways of phrasing this problem. – Mikhail Mar 01 '13 at 03:54

3 Answers3

4

You can use .format:

>>> class order(object) : pass
... 
>>> a = order()
>>> a.id=3
>>> "{order.id}".format(order=a)
'3'
>>> "{order.id} and then a {foo} hit the {baz} ".format(baz="fan",foo="rocket",order=a) 
'3 and then a rocket hit the fan '

This uses keyword arguments which are unordered by nature.

mgilson
  • 300,191
  • 65
  • 633
  • 696
1

Do you have a list of strings, or a dict? If it's an actual list, then you can't possibly do anything useful, because you don't know what value is what. But if it's a dict, you have a few options. Using the % operator:

"Order number %(order_id)s, price: %(price)s" % dict(order_id=3, price=4.00)

But I notice you have order.id in your example, which sounds like it means order is some custom object. In that case you can use the newer .format method, which lets you look up attributes right in the string:

"Order number {order.id}, price: {price}".format(order=..., price=...)
Eevee
  • 47,412
  • 11
  • 95
  • 127
0

This assumes that order and price are integers. You can use any other format specifier in place of d. (i.e. f for float)

string = "Order id %(order)d, price: %(price)d" % {'price': price, 'order': order}
Michael Mior
  • 28,107
  • 9
  • 89
  • 113