Borislav Hadzhiev
Last updated: Jul 9, 2022
Photo from Unsplash
To repeat a string to a certain length:
0
up to the
specified length.# 👇️ slightly faster for longer strings # also more difficult to read 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 # ---------------------- # 👇️ slightly slower for longer strings # much easier to read 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
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
result 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
.
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.