Is python += string concatenation bad practice?

后端 未结 1 920
无人及你
无人及你 2020-12-03 09:50

I am reading The Hitchhiker’s Guide to Python and there is a short code snippet

foo = \'foo\'
bar = \'bar\'

foobar = foo + bar  # This is good
foo += \'ooo         


        
相关标签:
1条回答
  • 2020-12-03 10:00

    Is it bad practice?

    It's reasonable to assume that it isn't bad practice for this example because:

    • The author doesn't give any reason. Maybe it's just disliked by him/her.
    • Python documentation doesn't mention it's bad practice (from what I've seen).
    • foo += 'ooo' is just as readable (according to me) and is approximately 100 times faster than foo = ''.join([foo, 'ooo']).

    When should one be used over the other?

    Concatenation of strings have the disadvantage of needing to create a new string and allocate new memory for every concatenation! This is time consuming, but isn't that big of a deal with few and small strings. When you know the number of strings to concatenate and don't need more than maybe 2-4 concatenations I'd go for it.


    When joining strings Python only has to allocate new memory for the final string, which is much more efficient, but could take longer to compute. Also, because strings are immutable it's often more practical to use a list of strings to dynamically mutate, and only convert it to a string when needed.

    It's often convenient to create strings with str.join() since it takes an iterable. For example:

    letters = ", ".join("abcdefghij")
    

    To conclude

    In most cases it makes more sense to use str.join() but there are times when concatenation is just as viable. Using any form of string concatenation for huge or many strings would be bad practice just as using str.join() would be bad practice for short and few strings, in my own opinion.

    I believe that the author was just trying to create a rule of thumb to easier identify when to use what without going in too much detail or make it complicated.

    0 讨论(0)
提交回复
热议问题