String concatenation vs. string substitution in Python

前端 未结 9 1622
暖寄归人
暖寄归人 2020-11-29 17:13

In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (

相关标签:
9条回答
  • 2020-11-29 17:58

    Actually the correct thing to do, in this case (building paths) is to use os.path.join. Not string concatenation or interpolation

    0 讨论(0)
  • 2020-11-29 18:03

    Be wary of concatenating strings in a loop! The cost of string concatenation is proportional to the length of the result. Looping leads you straight to the land of N-squared. Some languages will optimize concatenation to the most recently allocated string, but it's risky to count on the compiler to optimize your quadratic algorithm down to linear. Best to use the primitive (join?) that takes an entire list of strings, does a single allocation, and concatenates them all in one go.

    0 讨论(0)
  • 2020-11-29 18:05

    I use substitution wherever I can. I only use concatenation if I'm building a string up in say a for-loop.

    0 讨论(0)
提交回复
热议问题