With a string and a binary list of the same length, for example:
[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
s t a c k o v e r f l o w
Is it possible to obtain a new string as -t-c-over----
that follows:
[0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
- t - c - o v e r - - - -
That is, each character matching with 0
will be replaced as -
. The desired output would be a list as below with letters matching 1
and hyphens matching 0
are grouped separately:
['-', 't', '-', 'c', '-', 'over', '----']
Thanks!
How about something like this? Zip the two lists and iterate and build the output. Keep the last binary value to determine whether you should append or concat.
blist = [0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
string = 'stackoverflow'
output = []
previous = not blist[0] # to cause the first char to be appended
for b,s in zip(blist, string):
char = '-' if b == 0 else s
if previous == b:
output[-1] += char
else:
output.append(char)
previous = b
print(output)
Another option is regex:
import re
blist = [0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0]
string = 'stackoverflow'
x = ''.join(['-' if b == 0 else s for b,s in zip(blist, string)])
output = re.findall('(-+|[a-z]+)', x)
print(output)
You can have fun with iterators (no zip needed! :)
it = iter([0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0])
s = 'stackoverflow'
output = [''.join(('-' for i in b) if not a else b)
for a,b in
itertools.groupby(s, key=lambda x: next(it))]
So output will be:
['-', 't', '-', 'c', '-', 'over', '----']
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