Is there an idiom for join () with head or tail?

''. join (list) is pretty big. However, I notice that I very often have to add extra characters to the beginning and end. I did this in several ways, but it seems to me that there is a more readable way that I cannot think of.

Is there an elegant way to handle it? Did I just change my mind about this?

For instance:

["column1", "column2", "column3"] 

Required Conclusion:

  | column1 | column2 | column3 | 

Code without beginning and end (short!)

 print ' | '.join(mylist) 

With head and tail:

 print ' | ' + ' | '.join(mylist) + ' | ' print ' | ', ' | '.join(mylist), ' | ' print " | {} | ".format(' | '.join(mylist)) print ' | '.join([''] + mylist + ['']) (ugh) 
+4
source share
5 answers

I do not see a better way than the approaches that you have already found. Here is my preference, fixing the error when you entered extra space at the beginning and at the end:

 print ' |' + ' | '.join(list) + '| ' 

What is inconvenient for you? Is it readability? Need to repeat yourself when you create the same line in different places? If so, the answer to both of them is to pack this line as a function and use its callers.

+3
source

I think the third option is a closet, which you can get:

 print " | {} | ".format(' | '.join(list)) 
+3
source

Another option:

 " | " + "".join(x + " | " for x in lst) 

I donโ€™t think there is one โ€œgoodโ€ way to do this. If you need it a lot, write a function to do what you need.

0
source

If you need one line:

 print "| %s |" % (' | '.join(list)) 

But probably rethinking it.

0
source

Adding extra blank lines at the beginning and end of the list may allow you to join without โ€œrepeatingโ€ - you can still change the delimiter by changing one character.

 " | ".join([""] + lst + [""]) 

Or avoid a temporary list if lst is large:

 from itertools import chain " | ".join(chain([""], lst, [""]) 
0
source

Source: https://habr.com/ru/post/1393261/


All Articles