Ad

Is There A More Efficent Way To Extend A String?

- 1 answer

Does anybody know of a more efficent way to extend a string, eg fred, to be the length of the string plaintext - so that fred would become fredfredf - than this?

# key='fred', msg='plaintext'?

def keypad(key, msg):
    while len(key) < len(msg):
        key += key
    key = key[:len(msg)]
    return key
Ad

Answer

No import needed, creates as few things as possible. Might be better then Austins solution (no imports, longer sourcecode):

key='fred'
msg='plaintext'

def keypad(key, msg):
    lk = len(key)
    lm = len(msg) 
    return ''.join( [ key[idx%lk] for idx in range(lm) ] )

print(keypad(key,msg))
# fredfredf

Leveraging the modulo division on the key-text in combination with a list (.join() would convert the generator to a list internally anyway - so faster to use a list in the first place - cudos to @Austin's comment).

Advantage:

  • no imports
  • no string slicing
  • uses generator, so no intermediate string creations (just one at the end)
  • no overshooting to be sliced away

Suggested read:

List vs generator comprehension speed with join function for speed of join() for list vs generator

Ad
source: stackoverflow.com
Ad