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?

7
  • 1
    if some_file_name isn't a string, the f string or format method are easier to use. Commented May 17, 2019 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. Commented May 17, 2019 at 14:55
  • This link may help realpython.com/python-string-formatting/… Commented May 17, 2019 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. Commented May 17, 2019 at 14:57
  • 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. Commented May 17, 2019 at 15:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.