0
def foo(string, **kwargs):
  return string % kwargs  # simplified a much more complex SQL query function with argument binding.

string = '%(a)s %(b)s.'
print foo(string %{'a': 'Hello'}, b='world')

I want to achieve this '%(a)s %(b)s' => 'Hello %(b)s' => 'Hello world' (and not '%(a)s %(b)s' => 'Hello world' in one go).

Is there anyway in python to make it work?

3
  • The % operator is not officially deprecated but newer code is supposed to use the new string format spec mini-language Commented Dec 10, 2014 at 1:13
  • This is outside the scope of the question, but I have put the answer based on your comment below. Commented Dec 10, 2014 at 1:27
  • BTW, you may want to check sqlalchemy.sql - personally I find it better than interpolating strings. If not for the convenience, it is worth just for the portability and security (are you sure you are handling every injection technique out there?) Commented Dec 10, 2014 at 6:38

1 Answer 1

4

Just double the %:

string = '%(a)s %%(b)s.'

If you want to use the new string formatting spec, then you can similarly double the braces:

def foo(string, **kwargs):
  return string.format(**kwargs ) # simplified a much more complex SQL query function with argument binding.

string = '{a} {{b}}.'
print foo(string.format(a='Hello'), b='world')

prints: 
Hello world.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.