Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
which is "better"?
#1
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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'
Recommended Tutorials:
Reply
#3
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
f-string in 3.6 is nice.
>>> pair = ('foo','bar')
>>> f"prefix_{'_'.join(pair)}"
'prefix_foo_bar'
Reply
#5
it is a variable number, so join is the way, but which of the 2 i showed?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#6
Quote:it is a variable number, so join is the way, but which of the 2 i showed?
neither -- snippsat's is best
Reply
#7
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.
Recommended Tutorials:
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020