I am trying to format a message by repeating its items according to a pattern:
message = '123'
pattern = '** *** **** * **'
Expected output : 12 312 3123 1 23
Below is my current code, but is outputs: 123 12 31 231 23
def main():
message = "123"
pattern = "** *** ** ** *"
print(patterned_message(message, pattern))
def patterned_message(message, pattern):
c = 0
res = ""
jstr = [x.strip(" ") for x in message]
for i in pattern:
if c == (len(jstr)):
c = 0
else:
if i == " ":
res = " "
else:
res = i.replace("*","{}".format(jstr[c]))
c = 1
return res
if __name__ == '__main__':
main()
CodePudding user response:
You can use itertools.cycle
as a generator and a small list comprehension:
from itertools import cycle
message = '123'
pattern = '** *** **** * **'
x = cycle(message)
out = ''.join(next(x) if i == '*' else ' ' for i in pattern)
print(out)
output: '12 312 3123 1 23'
Just for python learners, here is a more classical approach:
def patterned_message(message, pattern):
out = [' ']*len(pattern)
n = 0
for i, char in enumerate(pattern):
if char == '*':
out[i] = message[n%len(message)]
n =1
return ''.join(out)
patterned_message('123', '** *** **** * **')