【问题标题】:python how can string .replace() only calc the new value if the old value is found in the string如果在字符串中找到旧值,python如何字符串.replace()只计算新值
【发布时间】:2022-06-17 00:02:18
【问题描述】:

我有一个类似这样的代码:

str = some_template
str = str.replace('<HOLDER1>',data1)
str = str.replace('<HOLDER2>',data2)
str = str.replace('<HOLDER4>',data3)
... #(about 30 similar lines)

其中 data1/data2/etc 通常是对可能需要一段时间来计算的函数的调用。例如:

str = str.replace('&lt;HOLDER5&gt;',calc_factorial(1000))

为了节省运行时间,我希望 string.replace() 方法仅在 str 中找到旧值时才计算新值。这可以通过以下方式实现:

if '<HOLDER1>' in str:
    str = str.replace('<HOLDER1>',data1)
if '<HOLDER2>' in str:
    str = str.replace('<HOLDER2>',data2)
if '<HOLDER3>' in str:
    str = str.replace('<HOLDER3>',data3)
...

但我不喜欢这种解决方案,因为它需要双倍的代码行数,这将是非常混乱的,并且还会为每个持有者两次在 str 中找到旧值..

有什么想法吗?

谢谢!

【问题讨论】:

  • 是什么让你觉得这更快?

标签: python string function


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-09
  • 1970-01-01
  • 2018-08-23
  • 2020-01-03
  • 2021-06-28
  • 1970-01-01
  • 2017-12-25
相关资源
最近更新 更多