What is an efficient way to repeat a string to a certain length in Python?

PythonServer Side ProgrammingProgramming

If you want the string to repeat to n characters, then you can first repeat the whole string to n/len(s) times and add the n%len(s) characters at the end. For example,

def repeat_n(string, n):
    l = len(s)
    full_rep = n/l
       # Construct string with full repetitions
    ans = ''.join(string for i in xrange(full_rep))
    # add the string with remaining characters at the end.
    return ans + string[:n%l]
repeat_n('asdf', 10)

This will give the output:

'asdfasdfas'

You can also make use of '*' operation on string to repeat the string. For example,

def repeat_n(string_to_expand, n):
   return (string_to_expand * ((n/len(string_to_expand))+1))[:n]
repeat_n('asdf', 10)

This will give the output:

'asdfasdfas'
raja
Updated on 30-Sep-2019 08:16:21

Advertisements