3

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
user797963
  • 2,907
  • 9
  • 47
  • 88
  • 1
    if `some_file_name` isn't a string, the f string or format method are easier to use. – SuperStew May 17 '19 at 14:55
  • 4
    `+` 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 or `format()` allow for lots of detailed controls -- padding, format conversion, etc. And you get errors if you pass a type that needs to have `str()` called it on it before it can be added to a string, *unless* you use a formatting mechanism that does that for you. – Charles Duffy May 17 '19 at 14:55
  • This link may help https://realpython.com/python-string-formatting/#3-string-interpolation-f-strings-python-36 – smitty_werbenjagermanjensen May 17 '19 at 14:56
  • ...so, if you get in the habit of using `+`, 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. – Charles Duffy May 17 '19 at 14:57
  • Anybody sure if `file_name = some_file_name + ".yaml"` will create a throwaway `".yaml"` string before concatting? That would be a minor drawback – Patrick Artner May 17 '19 at 14:58
  • 4
    Also, `'{}-{}.yaml'.format(s1, s2)` and `f'{s1}-{s2}.yaml'` are more efficient than `s1 + "-" + s2 + ".yaml"`, which creates multiple temporary `str` objects as each `+` is evaluated. – chepner May 17 '19 at 15:01
  • Also https://stackoverflow.com/questions/38722105/format-strings-vs-concatenation – sanyassh May 17 '19 at 15:05

0 Answers0