Python | Range duplication in String
Last Updated :
12 Apr, 2023
Sometimes, while working with Strings, we can have a problem in which we need to replicate the range of strings consecutively in range. This kind of problem can have applications in day-day programming domain. Let us discuss the certain ways in which this task can be performed.
Method: Using string slicing
This is straight forward way to solve this problem. In this, we perform the task of slicing the string to be repeated and attach its duplicate. The pre and post slices are attached to its prefix and suffix respectively to construct the result string.
Python3
test_str = "geeksforgeeks"
print ( "The original string is : " + test_str)
i, j = 3 , 6
temp = test_str[i:j] * 2
res = test_str[:i] + temp + test_str[j:]
print ( "The string after range duplication : " + res)
|
Output :
The original string is : geeksforgeeks
The string after range duplication : geeksfksforgeeks
Time Complexity: O(n) -> slicing
Auxiliary Space: O(n)
Method #2: Using string formatting with multiplication
Step-by-step algorithm:
- Initialize the input string.
- Initialize the start and end indices of the range to be duplicated.
- Perform the range duplication in string using string formatting with multiplication and store the result in temp variable.
- Concatenate the temp variable with the string before and after the range to get the final string and store it in the res variable.
- Print the final string after range duplication.
Python3
test_str = "geeksforgeeks"
print ( "The original string is : " + test_str)
i, j = 3 , 6
temp = "{}{}" . format (test_str[i:j], test_str[i:j])
res = "{}{}{}" . format (test_str[:i], temp, test_str[j:])
print ( "The string after range duplication : " + res)
|
Output
The original string is : geeksforgeeks
The string after range duplication : geeksfksforgeeks
Time Complexity: O(1)
Space Complexity: O(1)
Method #3: Using string.split() and string.join()
- Initializing the input string, test_str, and the indices i and j
- Split the string into three parts using split(): the characters before index i, the characters between i and j (inclusive), and the characters after index j.
- Duplicate the middle part of the string using string concatenation, then join the three parts back together using join().
- Print the original string and the modified string as output.
Python3
test_str = "geeksforgeeks"
print ( "The original string is : " + test_str)
i, j = 3 , 6
substr = test_str[i:j]
res = test_str.split(substr)
res.insert( 1 , substr * 2 )
res = ''.join(res)
print ( "The string after range duplication : " + res)
|
Output
The original string is : geeksforgeeks
The string after range duplication : geeksfksforgeeks
The time complexity is O(n) where n is the length of the string.
The auxiliary space is O(n) where n is the length of the string.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...