Format strings vs concatenation

前端 未结 7 670
天命终不由人
天命终不由人 2020-11-28 09:18

I see many people using format strings like this:

root = \"sample\"
output = \"output\"
path = \"{}/{}\".format(root, output)

Instead of si

7条回答
  •  我在风中等你
    2020-11-28 09:39

    As with most things, there will be a performance difference, but ask yourself "Does it really matter if this is ns faster?". The root + '/' output method is quick and easy to type out. But this can get hard to read real quick when you have multiple variables to print out

    foo = "X = " + myX + " | Y = " + someY + " Z = " + Z.toString()
    

    vs

    foo = "X = {} | Y= {} | Z = {}".format(myX, someY, Z.toString())
    

    Which is easier to understand what is going on? Unless you really need to eak out performance, chose the way that will be easiest for people to read and understand

提交回复
热议问题