How to repeat a String N times in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
7 min

banner

# Table of Contents

  1. Repeat a string N times in Python
  2. Repeat a String to a certain Length in Python
  3. Repeat a String N times with a Separator in Python
  4. Repeat each character in a string N times in Python

# Repeat a string N times in Python

Use the multiplication operator to repeat a string N times, e.g. new_str = my_str * 2.

The multiplication operator will repeat the string the specified number of times and will return the result.

main.py
my_str = 'bobby' # โœ… Repeat a string N times new_str = my_str * 2 print(new_str) # ๐Ÿ‘‰๏ธ bobbybobby # --------------------------------------- # โœ… Repeat a substring N times new_str = my_str[0:3] * 2 print(new_str) # ๐Ÿ‘‰๏ธ bobbob # --------------------------------------- # โœ… Repeat a string N times with a separator new_str = ' '.join([my_str] * 2) print(new_str) # ๐Ÿ‘‰๏ธ bobby bobby

repeat string n times

The code for this article is available on GitHub

The first example uses the multiplication operator to repeat a string N times.

When the multiplication operator is used with a string and an integer, it repeats the string the specified number of times.

main.py
print('ab-' * 2) # ๐Ÿ‘‰๏ธ ab-ab- print('ab-' * 3) # ๐Ÿ‘‰๏ธ ab-ab-ab-

If you need to repeat a substring N times, use string slicing.

main.py
my_str = 'bobby' new_str = my_str[0:3] * 2 print(new_str) # ๐Ÿ‘‰๏ธ bobbob

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

# Repeat an integer multiple times using the multiplication operator

If you need to print an integer multiple times, make sure to convert it to a string before using the multiplication operator.

main.py
my_int = 9 print(str(my_int) * 4) # ๐Ÿ‘‰๏ธ '9999'

repeat integer multiple times using multiplication operator

The code for this article is available on GitHub
We used the str() class to convert the integer to a string before multiplying it by 4.

# Repeat a string multiple times using a formatted string literal

You can also use a formatted string literal to print a string multiple times.

main.py
my_str = 'z' result = f'Result: {my_str * 4}' print(result) # ๐Ÿ‘‰๏ธ Result: zzzz

repeat string multiple times using f-string

The code for this article is available on GitHub

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
my_num = 100 print(f'{my_num}' * 2) # ๐Ÿ‘‰๏ธ 100100 print(f'{my_num} ' * 2) # ๐Ÿ‘‰๏ธ 100 100

Make sure to wrap expressions in curly braces - {expression}.

# Repeat a string to a certain length in Python

To repeat a string to a certain length:

  1. Multiply the string by the specified length to repeat it N times.
  2. Use string slicing to select a part of the string from index 0 up to the specified length.
main.py
def repeat_to_length(string, length): return (string * (length//len(string) + 1))[:length] print(repeat_to_length('asd', 6)) # ๐Ÿ‘‰๏ธ asdasd print(repeat_to_length('asd', 4)) # ๐Ÿ‘‰๏ธ asda

repeat string to certain length

The code for this article is available on GitHub

The first thing to note is that we can repeat a string by multiplying it with an integer.

main.py
print('asd' * 2) # ๐Ÿ‘‰๏ธ 'asdasd'

The first function aims to repeat the string fewer times and might be a little faster for longer strings.

main.py
def repeat_to_length(string, length): return (string * (length//len(string) + 1))[:length] print(repeat_to_length('asd', 6)) # ๐Ÿ‘‰๏ธ asdasd print(repeat_to_length('asd', 4)) # ๐Ÿ‘‰๏ธ asda

The function takes the string and the desired length as arguments and repeats the string to the specified length.

We used the floor division // operator to get an integer from the division.

Division / of integers yields a float, while floor division // of integers results in an integer.

The result of using the floor division operator is that of a mathematical division with the floor() function applied to the result.

This is important because division / of integers always returns a float, and trying to multiply a string by a float would raise a TypeError.

The last step is to use string slicing to get a part of the string from index 0 up to the specified length.

main.py
print('asdasd'[:4]) # ๐Ÿ‘‰๏ธ 'asda' print('asdasd'[:3]) # ๐Ÿ‘‰๏ธ 'asd'

The syntax for string slicing is my_str[start:stop:step], where the start value is inclusive and the stop value is exclusive.

This is exactly what we need because indexes are zero-based in Python. In other words, the last index in a string is len(my_str) - 1.

# Repeat a string to a certain length by multiplying

Alternatively, you can use a simpler and more direct approach by multiplying the string by the provided length and getting a slice of the string up to the specified length.

main.py
def repeat_to_length_2(string, length): return (string * length)[:length] print(repeat_to_length_2('asd', 6)) # ๐Ÿ‘‰๏ธ asdasd print(repeat_to_length_2('asd', 4)) # ๐Ÿ‘‰๏ธ asda

repeat string to certain length by multiplying

The code for this article is available on GitHub

We multiply the string by the specified length to repeat it N times.

The string is repeated many more times than necessary, but this is probably not going to be an issue if working with relatively short strings.

main.py
# ๐Ÿ‘‡๏ธ asdasdasdasdasdasd print('asd' * 6) # ๐Ÿ‘‡๏ธ asdasd print('asdasdasdasdasdasd'[:6])

This approach might be slower for longer strings, but it is much easier to read.

# Repeat a string N times with a separator in Python

If you need to repeat a string N times with a separator:

  1. Wrap the string in a list and multiply it by N.
  2. Use the str.join() method to join the list of strings.
  3. The str.join() method will join the repeated strings with the provided separator.
main.py
my_str = 'bobby' new_str = ' '.join([my_str] * 2) print(new_str) # ๐Ÿ‘‰๏ธ bobby bobby new_str = ' '.join([my_str] * 3) print(new_str) # ๐Ÿ‘‰๏ธ bobby bobby bobby new_str = '-'.join([my_str] * 2) print(new_str) # ๐Ÿ‘‰๏ธ bobby-bobby

We wrapped the string in square brackets to pass a list to the str.join() method.

When the multiplication (*) operator is used with a list and an integer, it repeats the items in the list N times.
main.py
print(['bobby'] * 2) # ๐Ÿ‘‰๏ธ ['bobby', 'bobby'] print(['bobby'] * 3) # ๐Ÿ‘‰๏ธ ['bobby', 'bobby', 'bobby'] print(['a', 'b'] * 2) # ๐Ÿ‘‰๏ธ ['a', 'b', 'a', 'b']

Once we have a list containing the string N times, we can use the str.join() method.

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

main.py
my_str = 'bobby' new_str = ' '.join([my_str] * 2) print(new_str) # ๐Ÿ‘‰๏ธ bobby bobby

The string the method is called on is used as the separator between the elements.

main.py
my_str = 'bobby' new_str = '-'.join([my_str] * 2) print(new_str) # ๐Ÿ‘‰๏ธ bobby-bobby

If you need to repeat a slice of a string N times with a separator, use string slicing.

main.py
my_str = 'bobbyhadz.com' new_str = ' '.join([my_str[0:5]] * 2) print(new_str) # ๐Ÿ‘‰๏ธ bobby bobby

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

The slice my_str[0:5] starts at index 0 and goes up to, but not including index 5.

main.py
my_str = 'bobbyhadz.com' print(my_str[0:5]) # ๐Ÿ‘‰๏ธ 'bobby'

Make sure to wrap the slice in square brackets to pass a list to the str.join() method.

main.py
my_str = 'bobbyhadz.com' new_str = ' '.join([my_str[0:5]] * 2) print(new_str) # ๐Ÿ‘‰๏ธ bobby bobby

If you pass a string to the method, the string would get split on each character.

If you use the more manual approach of adding the separator with the addition (+) operator and using the multiplication operator, you'd get a trailing separator.

main.py
my_str = 'bobby' new_str = (my_str + '-') * 3 print(new_str) # ๐Ÿ‘‰๏ธ bobby-bobby-bobby-

Notice that there is a hyphen at the end of the string.

You could use the str.rstrip() method to remove the hyphen, but the str.join() method approach is more elegant and intuitive.

# Repeat each character in a string N times in Python

To repeat each character in a string N times:

  1. Use a generator expression to iterate over the string.
  2. Use the multiplication operator to repeat each character N times.
  3. Use the str.join() method to join the object into a string.
main.py
my_str = 'asd' N = 2 new_str = ''.join(char * N for char in my_str) print(new_str) # ๐Ÿ‘‰๏ธ aassdd
The code for this article is available on GitHub

We used a generator expression to iterate over the string.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use the multiplication operator to repeat the character N times.

main.py
my_str = 'asd' # ๐Ÿ‘‡๏ธ ['aa', 'ss', 'dd'] print([char * 2 for char in my_str])

The last step is to use the str.join() method to join the strings in the generator object into a single string.

main.py
my_str = 'asd' N = 3 new_str = ''.join(char * N for char in my_str) print(new_str) # ๐Ÿ‘‰๏ธ aaasssddd

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

We used an empty string as the separator to join the strings in the generator object without a delimiter.

Alternatively, you can use the map() function.

# Repeat each character in a string N times using map()

This is a three-step process:

  1. Pass a lambda function and the string to the map() function.
  2. The lambda function should repeat each character N times.
  3. Use the str.join() method to join the map object into a string.
main.py
my_str = 'asd' N = 3 new_str = ''.join(map(lambda char: char * N, my_str)) print(new_str) # ๐Ÿ‘‰๏ธ aaasssddd
The code for this article is available on GitHub

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The lambda function we passed to map gets called with each character in the string.

The function uses the multiplication operator to repeat the character N times and returns the result.

The last step is to use the str.join() method to join the map object into a string.

Which approach you pick is a matter of personal preference. I'd use a generator expression because I find them quite direct and easy to read.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev