Python | Repeat String till K
Last Updated : 21 Apr, 2023
Sometimes, while working with strings, we might encounter a use case in which we need to repeat our string to the size of K, even though the last string might not be complete, but has to stop as the size of string becomes K. The problem of repeating string K times, is comparatively simpler than this problem. Let's discuss way outs we can perform to solve this problem.
Method #1 : Using list slicing and // operator
This task can be performed using the above tools. In this we just multiply the string till it becomes greater than or equal to K, and then just omit the slice of extra string using the list slicing method.
Python3 # Python3 code to demonstrate # Repeat string till K # using list slicing and // operator # initializing string test_string = "GeeksforGeeks" # initializing K K = 30 # printing original string print("The original string : " + str(test_string)) # using list slicing and // operator # Repeat string till K res = (test_string * (K//len(test_string) + 1))[:K] # print result print("String after performing repetition : " + res)
Output : The original string : GeeksforGeeks String after performing repetition : GeeksforGeeksGeeksforGeeksGeek
Time complexity: O(n)
Auxiliary space: O(n)
Method #2 : Using divmod() + list slicing
The division applied in the above method can be substituted in this method with the divmod function, which improves code readability with the cost of 40% of performance degradation.
Python3 # Python3 code to demonstrate # Repeat string till K # using divmod() + list slicing # initializing string test_string = "GeeksforGeeks" # initializing K K = 30 # printing original string print("The original string : " + str(test_string)) # using divmod() + list slicing # Repeat string till K div, mod = divmod(K, len(test_string)) res = test_string * div + test_string[:mod] # print result print("String after performing repetition : " + res)
Output : The original string : GeeksforGeeks String after performing repetition : GeeksforGeeksGeeksforGeeksGeek
Time complexity: O(1) since the operations are not dependent on the size of the input.
Auxiliary space: O(len(test_string)) since we create a string of length len(test_string) to store the repeated string.
Method #3: Using while loop and slicing
Python3 # Python3 code to demonstrate # Repeat string till K # initializing string test_string = "GeeksforGeeks" # initializing K K = 30 # printing original string print("The original string : " + str(test_string)) res = "" while(len(res) <= K): res += test_string # print result print("String after performing repetition : " + res[:K])
OutputThe original string : GeeksforGeeks String after performing repetition : GeeksforGeeksGeeksforGeeksGeek
Time complexity: O(K), where K is the maximum length of the repeated string.
Auxiliary space: O(K), as we are creating a new string 'res' to store the repeated string, and its maximum length can be K.
Method 4 : use the math module to determine the number of times the string needs to be repeated to reach the desired length, and then concatenate the string accordingly.
step-by-step approach:
Import the math module.
Initialize the original string and the desired length K.
Calculate the length of the original string using the len() function.
Calculate the number of times the original string needs to be repeated to reach the desired length using the math.ceil() function, which rounds up the result to the nearest integer.
Concatenate the original string the required number of times using string multiplication.
Trim the concatenated string to the desired length K using list slicing.
Print the final string.
Python3 import math # initializing string test_string = "GeeksforGeeks" # initializing K K = 30 # calculating length of original string length = len(test_string) # calculating number of repetitions required repetitions = math.ceil(K/length) # concatenating the string the required number of times res = test_string * repetitions # trimming the concatenated string to the desired length res = res[:K] # print result print("String after performing repetition : " + res)
OutputString after performing repetition : GeeksforGeeksGeeksforGeeksGeek
Time complexity: The time complexity of this approach is O(K), where K is the maximum length of the repeated string.
Auxiliary space: The auxiliary space used by this approach is also O(K),
Similar Reads
How to Repeat a String in Python?
Repeating a string is a simple task in Python. We can create multiple copies of a string by using built-in features. This is useful when we need to repeat a word, phrase, or any other string a specific number of times. Using Multiplication Operator (*):Using Multiplication operator (*) is the simple
2 min read
Python - Check if string repeats itself
Checking if a string repeats itself means determining whether the string consists of multiple repetitions of a smaller substring. Using slicing and multiplicationWe can check if the string is a repetition of a substring by slicing and reconstructing the string using multiplication. [GFGTABS] Python
3 min read
Reverse Sort a String - Python
The goal is to take a given string and arrange its characters in descending order based on their Unicode values. For example, in the string "geeksforgeeks", the characters will be sorted from highest to lowest, resulting in a new string like "ssrokkggfeeeee". Let's understand different methods to pe
2 min read
Python | Split by repeating substring
Sometimes, while working with Python strings, we can have a problem in which we need to perform splitting. This can be of a custom nature. In this, we can have a split in which we need to split by all the repetitions. This can have applications in many domains. Let us discuss certain ways in which t
5 min read
Python - Kth Valid String
Sometimes while dealing with data science, we need to handle a large amount of data and hence we may require shorthands to perform certain tasks. We handle the Null values at preprocessing stage and hence sometimes require to check for the Kth valid element. Letâs discuss certain ways in which we ca
3 min read
Python - Reversed Split Strings
In Python, there are times where we need to split a given string into individual words and reverse the order of these words while preserving the order of characters within each word. For example, given the input string "learn python with gfg", the desired output would be "gfg with python learn". Let
3 min read
How to copy a string in Python
Creating a copy of a string is useful when we need a duplicate of a string to work with while keeping the original string intact, strings in Python are immutable which means they can't be altered after creation, so creating a copy sometimes becomes a necessity for specific use cases. Using SlicingSl
2 min read
Python - Phrase removal in String
Sometimes, while working with Python strings, we can have a problem in which we need to extract certain words in a string excluding the initial and rear K words. This can have application in many domains including all those include data. Lets discuss certain ways in which this task can be performed.
2 min read
How to Count Repeated Words in a String in Python
In this article, we will learn how to count repeated words in a string. Python provides several methods to Count Repeated Words , such as dictionaries, collections. Counter module, or even regular expressions. The simplest way to count repeated words is by splitting the string into individual words
2 min read
Convert String to Tuple - Python
When we want to break down a string into its individual characters and store each character as an element in a tuple, we can use the tuple() function directly on the string. Strings in Python are iterable, which means that when we pass a string to the tuple() function, it iterates over each characte
2 min read