3

Consider the strings

string_0 = '%s test'
string_1 = '{} test'

Imagine now the desired output is to return the formatted string using the variable x = 'A'.

For the first case there is an easy and elegant solution:

string_0 %= x
print(string_0)
# A test

Is there something similar for the second case? E.g.

string_1 f= x    # Unfortunately does not work
print(string_1)
# A test

Addressing the comments/responses

  1. I realise string_1 is not an f-string but Python won't allow f-strings with empty expression
  2. I know f'{x} test' works perfectly well but requires knowing x before the creation.
  3. The format solutions is also something I'm familiar with but when comparing s = s.format(x) to s %= x I find not very smooth

PS Anticipating the responses, I wanted to edit the above part in my question but was not able due to the simultaneous edit.

user101
  • 476
  • 1
  • 4
  • 9

2 Answers2

1

New-style string formatting doesn't use an operator and therefore doesn't have an __i*__-method overloaded (as old-style formatting does with __imod__).

You could directly use an f-string:

string_1 = f"{x} test"

Other than that, you'll have to be explicit and use

string_1 = string_1.format(x)
L3viathan
  • 26,748
  • 2
  • 58
  • 81
1

Since strings are immutable, a %= b is pretty much exactly equivalent to a = a % b. The new style equivalent to the old style % operator is the format method:

string_1 = string_1.format(x)
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264