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

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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'
Updated on 30-Sep-2019 08:16:21