Python方法将参数列表转换为字符串

2024-04-20 04:45:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我继承了一些Python代码,它们从传入__init__的字符串参数构造字符串:

self.full_tag = prefix + number + point + suffix

也许我只是想了想,但这是连接论点的最好方法吗?我知道可以这样做:

^{pr2}$

或者只使用字符串格式函数:

^{3}$

Python的方法是什么?


Tags: 方法字符串代码selfnumber参数prefixinit
2条回答

Pythonic的方法是遵循The Zen of Python,关于这个案例有几点要说:

  • 美总比丑好。

  • 简单总比复杂好。

  • 可读性很重要。

再加上DonaldKnuth的名言:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

记住这些,你最好的选择是:

self.full_tag = prefix + number + point + suffix

虽然,如果数字真的是一个数字,而点确实是一个点,那么这是更明确的:

^{pr2}$
  • 显性胜于隐性。在

文档建议join+更好的性能:

6. ... For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.

如果说表现不是太重要,那更重要的是品位问题。在

就我个人而言,我发现"".joinformat版本中的所有大括号都更清晰易读。在

相关问题 更多 >