Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate through list of delimiters in join()

Tags:

python

How can I cycle through a list of delimiters in my string?

I'm trying to reference this post but am not following if enumerate is a correct approach.

my_list = range(11, 17)
# formats = ['#', '$', '%']
# How to implement formats?
my_string = '#'.join(map(str, my_list))
my_string

# have: '11#12#13#14#15#16'
# want: '11#12$13%14#15$16'
like image 375
md2614 Avatar asked Feb 02 '21 01:02

md2614


1 Answers

You could use itertools.cycle combined with zip:

from itertools import cycle

my_list = range(11, 17)
formats = cycle(['#', '$', '%'])

''.join(str(a) + b for a, b in zip(my_list, formats))

This produces '11#12$13%14#15$16%'. Notice the trailing % character.. you could drop that one manually, e.g. by slicing up to -1:

''.join(str(a) + b for a, b in zip(my_list, formats))[:-1]

By the way, if this is something you encounter a lot in your codebase, you might write a helper class, e.g.

from itertools import cycle


class MultiDelimiter:
    def __init__(self, *delimiters):
        self.delimiters = delimiters
        
    def join(self, strings):
        joined = ''.join(s + d for s, d in zip(strings, cycle(self.delimiters)))
        return joined[:-1]
    
            
my_list = ['11', '12', '13', '14', '15', '16']
            
delim = MultiDelimiter('#', '$', '%')
delim.join(my_list)  # returns: "11#12$13%14#15$16"

This uses the same convention as string.join, which helps in code readability / maintenance.

like image 94
Kris Avatar answered Sep 28 '22 22:09

Kris