5

String formatting expressions:

'This is %d %s example!' % (1, 'nice')

String formatting method calls:

'This is {0} {1} example!'.format(1, 'nice')

I personally prefer the method calls (second example) for readability but since it is new, there is some chance that one or the other of these may become deprecated over time. Which do you think is less likely to be deprecated?

1
  • When a new form is introduced, isn't is usually the old form that is deprecated? Commented Nov 19, 2009 at 13:26

3 Answers 3

8

Neither; the first one is used in a lot of places and the second one was just introduced. So the question is more which style you prefer. I actually prefer the dict based formatting:

d = { 'count': 1, 'txt': 'nice' }
'This is %(count)d %(txt)s example!' % d

It makes sure that the right parameter goes into the right place, allows to reuse the same parameter in several places, etc.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for dict-based approach. This can also be used with locals() and globals() to define the dict!
The dict-based approach can be emulated using the format() function, by passing **d to format(), and using {}.
6

I thought I read that the % operator is being deprecated in 3.1 already, so I'd stick with the format() function.

See PEP 3101: A New Approach To String Formatting

3 Comments

Huh? Where did you see that? There is nothing in the What's New at docs.python.org/3.1/whatsnew/3.1.html
I just know what the page said: it's going to be deprecated in 3.1 and removed at a later time...don't shoot the messenger :)
There is no mentioning of that in 3.1. :/
5

The original idea was to gradually switch to str.format() approach while allowing both ways:

PEP 3101:
The new system does not collide with any of the method names of the existing string formatting techniques, so both systems can co-exist until it comes time to deprecate the older system.

The idea is still being pursued:

We are still encouraging people to use the new str.format(). Python Issue 7343

Since the original '%' approach is planned to be deprecated and removed at some point in the future, I would suggest writing new code with str.format(). Though at the moment, it is just a matter of personal preference. I personally prefer using dictionary-based formatting, which is supported by both '%' operator and str.format() method.

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.