Python Forum

Full Version: which is "better"?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
any reason to believe one way is "better" than the other, for any definition of "better"?
    ...
    pair = ('foo','bar') # or it could be a longer tuple, always with strings
    ...
    foobar = '_'.join(('prefix',)+pair)
    foobar = 'prefix_'+('_'.join(pair))
normally i choose the code that is easier to read or the code that is shorter.  i ran into something like this, this evening, where they had the same ease to read and the same length.  maybe you have a "better" opinion.
i would prefer it like this
>>> '{}{}'.format('prefix_', '_'.join(pair))
'prefix_foo_bar'
Whereas concatenating it is messy and unreadable. This way you know 2 things are being input into the string, as well as know what they 2 are by what formats parameters are.

However if i knew the tuple was always going to be two elements, i would rather do this
>>> '{}_{}_{}'.format('prefix', *pair)
'prefix_foo_bar'
The format method is generally preferred over +, from what I can find it's more efficient:

foobar = 'prefix_{}'.format('_'.join(pair))
If you know it's going to be two things, I would go for full formatting:

foobar = 'prefix_{}_{}'.format(*pair)
However, if it's a variable number, join is better.
f-string in 3.6 is nice.
>>> pair = ('foo','bar')
>>> f"prefix_{'_'.join(pair)}"
'prefix_foo_bar'
it is a variable number, so join is the way, but which of the 2 i showed?
Quote:it is a variable number, so join is the way, but which of the 2 i showed?
neither -- snippsat's is best
i would say neither. I am not still yet fancy to use f strings but i would say either the f-string method or format method is better than both of yours.