开发者

Arguments in the middle of a string to be localized

I'm a beginner in Python. My problem is pretty simple. I have a string to be localized in a python application containing parameters :

print _('Hello dear user, your name is ') + params['first_name'] + ' ' + params['last_name'] + _(' and blah blah blah')

This actually d开发者_开发百科oes the job, but is not really what I would call a nice way to do it. Not to mention that some languages would, for example, require the last name to be displayed before the first name.

Is there a better way to do it ? I thought about placing custom tags like {{fn}} or {{ln}} in the translation string and replacing them by the actual values before displaying the string. But it seems not to be really more pleasant.

Thanks,

Pierre


I'd suggest

print 'Hello dear user, your name is %(first_name)s %(last_name)s' % params


Something like this should do the trick :

print _('Hello dear user, your name is %s %s and blah blah blah') % (params['first_name'], params['last_name'])


I would go with templates if I were you. That would let you have a separate template for each language. For example:

from string import Template
s_en = Template('Hello dear user, your name is $first_name $last_name and blah blah blah')
s_sco = Template('Hello, $first_name of the clan Mac$last_name...')

user = {'last_name': 'Duncan', 'first_name': 'Leod'}

print(s_en.substitute(user))
print(s_sco.substitute(user))


I thought about placing custom tags like {{fn}} or {{ln}} in the translation string and replacing them by the actual values before displaying them.

That's what I would do. Placeholders in the right places for each language versions should do the job.

One thing to mention that in some languages peoples names have to be modified dependent on where in a sentence and how they are used. You need to know each specific language to be able to do it correctly.

A possible solution: keep "in the middle of a sentence" cases to a minimum. Keep a localizable resource separated.

Instead of Hello dear user, your name is {{UserName}}

use User name: {{UserName}}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜