使用 Python 使用 gettext 进行字符串替换的最佳实践

发布于 2024-09-03 04:15:42 字数 485 浏览 4 评论 0原文

寻找有关使用 gettext() 时使用哪种字符串替换技术的最佳实践建议。或者所有技术都同样适用吗?

我至少可以想到 3 种字符串技术:

1) 基于经典“%”的格式:

“我的名字是 %(name)s” % locals()

2) 基于 .format() 的格式:

“我的名字是 {name}” .format( locals() )

3) string.Template.safe_substitute()

导入字符串 template = string.Template( "我的名字是 ${name}" ) template.safe_substitute( locals() )

string.Template 技术的优点是,带有拼写错误的变量引用的翻译字符串仍然可以产生可用的字符串值,而其他技术无条件引发异常。 string.Template 技术的缺点似乎是无法自定义变量的格式(填充、对齐、宽度等)。

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()

2) .format() based formatting:

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

3) 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).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

汹涌人海 2024-09-10 04:15:42

实际上,我更愿意在测试期间出现异常,以便尽快修复错误——“错误不应该悄无声息地传递”。所以我认为方法(2)是现代Python中最好的方法(它支持可读且灵活的格式),而方法(1)可能是不可避免的回退,如果你坚持支持旧版本Python 版本(其中 % 是进行灵活格式化的“”方式 - 查找或编码,format 的某些向后移植将是主要替代方案)。

Actually I would prefer to get an exception during my tests, to fix the error as soon as possible -- "errors should not pass silently". So I consider that approach (2) is the best one in modern Python (which supports the readable and flexible format), and approach (1) a probably inevitable fall-back if you're stuck supporting older Python releases (where % was "the" way to do flexible formatting -- finding, or coding, some backport of format would be the main alternative).

狂之美人 2024-09-10 04:15:42

不要有拼写错误的变量名——这就是测试的目的。

从表面上看,显示某些东西似乎比抛出异常更好,但迟早其中一个错误翻译必然会冒犯某些用户。

.format() 是当今的主流方式。

重新考虑将 locals() 直接传递到翻译中。如果有人想出一种方法在其中一个翻译中用 self 做一些偷偷摸摸的事情,这会让你不用担心会发生什么。

Don't have incorrectly spelled variable names - that's what testing is for.

On the face of it, displaying something seems better than throwing an exception, but sooner or later one of those mistranslations is bound to cause offence to some user.

.format() is the way to go these days.

Reconsider passing locals() straight into the translation. It will save you worrying about what happens if someone works out a way to do something sneaky with self in one of the translations.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文