Last updated: Apr 9, 2024
Reading timeยท7 min
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.
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
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.
print('ab-' * 2) # ๐๏ธ ab-ab- print('ab-' * 3) # ๐๏ธ ab-ab-ab-
If you need to repeat a substring N times, use string slicing.
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]
.
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
.
If you need to print an integer multiple times, make sure to convert it to a string before using the multiplication operator.
my_int = 9 print(str(my_int) * 4) # ๐๏ธ '9999'
str()
class to convert the integer to a string before multiplying it by 4.You can also use a formatted string literal to print a string multiple times.
my_str = 'z' result = f'Result: {my_str * 4}' print(result) # ๐๏ธ Result: zzzz
Formatted string literals (f-strings) let us include expressions inside of a
string by prefixing the string with f
.
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}
.
To repeat a string to a certain length:
0
up to the
specified length.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 first thing to note is that we can repeat a string by multiplying it with an integer.
print('asd' * 2) # ๐๏ธ 'asdasd'
The first function aims to repeat the string fewer times and might be a little faster for longer strings.
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.
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.
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
.
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
.
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
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.
# ๐๏ธ asdasdasdasdasdasd print('asd' * 6) # ๐๏ธ asdasd print('asdasdasdasdasdasd'[:6])
This approach might be slower for longer strings, but it is much easier to read.
If you need to repeat a string N times with a separator:
str.join()
method to join the list of strings.str.join()
method will join the repeated strings with the provided
separator.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.
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.
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.
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.
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]
.
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
.
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.
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.
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.
To repeat each character in a string N times:
str.join()
method to join the object into a string.my_str = 'asd' N = 2 new_str = ''.join(char * N for char in my_str) print(new_str) # ๐๏ธ aassdd
We used a generator expression to iterate over the string.
On each iteration, we use the multiplication operator to repeat the character N times.
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.
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.
This is a three-step process:
map()
function.str.join()
method to join the map
object into a string.my_str = 'asd' N = 3 new_str = ''.join(map(lambda char: char * N, my_str)) print(new_str) # ๐๏ธ aaasssddd
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.
You can learn more about the related topics by checking out the following tutorials: