Sulhan
Sulhan

Reputation: 116

Repeat binary number to be the same length as another number in python

Say I have a binary number message of 0100110101100101 and a binary key of 001.

How can I repeat the key to be the same length as the message? As in take the length of the message and then repeat the pattern of the key till the length of the message is reached?

In the example the output should be 0010010010010010

Thanks.

Upvotes: 1

Views: 187

Answers (1)

Mayank Porwal
Mayank Porwal

Reputation: 34086

You can use python's list slicing:

In [1599]: a = '0100110101100101'
In [1602]: key = '001'

In [1608]: factor = len(a) // len(key)
In [1606]: remainder = len(a) % len(key)

In [1625]: if factor == 0:
      ...:     print("pattern greater than the string")
      ...: else:
      ...:     answer = (key * factor) + key[:remainder]
      ...: 

In [1614]: answer
Out[1614]: '0010010010010010'

Upvotes: 1

Related Questions