When combining a variable and a string to be printed in Python, there seem to be a number of ways to do the same thing;
test = "Hello"
print "{} World".format(test) #Prints 'Hello World'
print test+" World" #Prints 'Hello World'
print "%s World" % test #Prints 'Hello World'
What (if any) is the difference between these methods in terms of performance, compatibility and general preference. Even between open source projects all three methods seem to be used interchangeably.
As you mentioned, various open source projects will use all of these methods for string formatting. However, I would stick to one method for one project so as not to confuse other developers with differing styles.
print test+" World"is the most efficient, performance-wise, but gives you the least amount flexibilityprint "%s World" % test #Prints 'Hello World'is basically like C’ssprintfwhich does string interpolation.I like to use this method a lot, because you can pass in not just a regular string, but a dictionary.
print "Good morning %(name), there are %(count)d new articles in %(topic)s today. Would you like to <a href='%(url)s'>read them</a>?" % valuesI haven’t used
"{} World".format(test)personally.In real applications, the performance difference between these methods are insignificant, and it’s really about adhering to style and not over-coding.