I feel like this would have been asked before, but could not find anything.
In python, if you want to insert a var into a string, there are (at least) two ways of doing so.
Using the +
operator
place = "Alaska"
adjective = "cold"
sentence = "I live in "+place+"! It's very "+adjective+"!"
# "I live in Alaska! It's very cold!"
And using a tuple
place = "Houston"
adjective = "humid"
sentence = "I live in %s! It's very %s!" % (place, adjective)
# "I live in Houston! It's very humid!"
Why would one use the tuple method over using +
? The tuple format seems a lot more obfuscated. Does it provide an advantage in some cases?
The only advantage I can think of is you don't have to cast types with the latter method, you can use %s
to refer to a
, where a = 42
, and it will just print it as a string, as opposed to using str(a)
. Still that hardly seems like a significant reason to sacrifice readability.