Best practice for string substition with gettext using Python

Posted by Malcolm on Stack Overflow See other posts from Stack Overflow or by Malcolm
Published on 2010-05-24T23:38:53Z Indexed on 2010/05/24 23:41 UTC
Read the original article Hit count: 271

Looking for best practice advice on what string substitution technique to use when using gettext(). Or do all techniques apply equally?

I can think of at least 3 string techniques:

  1. Classic "%" based formatting:

"My name is %(name)s" % locals()

  1. .format() based formatting:

"My name is {name}".format( locals() )

  1. string.Template.safe_substitute()

import string template = string.Template( "My name is ${name}" ) template.safe_substitute( locals() )

The advantage of the string.Template technique is that a translated string with with an incorrectly spelled variable reference can still yield a usable string value while the other techniques unconditionally raise an exception. The downside of the string.Template technique appears to be the inability for one to customize how a variable is formatted (padding, justification, width, etc).

© Stack Overflow or respective owner

Related posts about python

Related posts about string