I'm trying to actually learn python and use it for more than quick / dirty one-off scripts, and am wondering why is it best practice (or, is it even considered best practice) to use f-strings or string format instead of just using '+' for concatenation?
For example...
some_file_name = "abcd"
file_name = some_file_name + ".yaml"
file_name = f"{some_file_name}.yaml"
file_name = "{}.yaml".format(some_file_name)
What is the best practice here? Why not just use '+' to concatenate the variable and the string?
some_file_nameisn't a string, the f string or format method are easier to use.+is a lot more variable in how it behaves across types, and offers far less control. The case where you're just formatting things as a string is the simple case, but f-strings orformat()allow for lots of detailed controls -- padding, format conversion, etc. And you get errors if you pass a type that needs to havestr()called it on it before it can be added to a string, unless you use a formatting mechanism that does that for you.+, sometimes it'll work for you and sometimes it won't, but if you get in the habit of f-strings, it'll pretty much always be flexible enough that you can make it do what you want.'{}-{}.yaml'.format(s1, s2)andf'{s1}-{s2}.yaml'are more efficient thans1 + "-" + s2 + ".yaml", which creates multiple temporarystrobjects as each+is evaluated.