Less good then Austins solution, but better then yours:
Your approach is inefficient because you
- concat strings: the old one is destroyed and a new one created (over and over)
- you double the length of your combined string on each iteration (might get huge overshoot)
It would be better to calculate how often
key
fits into msg
and create only one resulting string (reducing the amount of created/destroyed strings) and also reducing the size of the resulting string.
key='fred'
msg='plaintext'
def keypad(key, msg):
l=len(msg) # store loally so you do not call len twice on it
mult = l//len(key) + 1
return (key*mult)[:l] # overshoots maximally by len(k)-1 characters
print(keypad(key,msg))
Strings created for:
key = "1234"
msg = "1234567890123456789"
we create
"12341234" # you, created, thrown away
"1234123412341234" # you, created, thrown away
"12341234123412341234123412341234" # you
"12341234123412341234" # me