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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With