Python - Retain first N Elements of a String and Replace the Remaining by K
Last Updated :
10 Mar, 2023
Given a String, retain first N elements and replace rest by K.
Input : test_str = 'geeksforgeeks', N = 5, K = "@"
Output : geeks@@@@@@@@
Explanation : First N elements retained and rest replaced by K.
Input : test_str = 'geeksforgeeks', N = 5, K = "*"
Output : geeks********
Explanation : First N elements retained and rest replaced by K.
Method #1 : Using * operator + len() + slicing
In this, slicing is used to retain N, and then the length of remaining is extracted by subtracting the total length extracted by len(), from N, and then repeat K char using * operator.
Python3
# Python3 code to demonstrate working of
# Retain N and Replace remaining by K
# Using * operator + len() + slicing
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing length needed
N = 4
# initializing remains char
K = "@"
# using len() and * operator to solve problem
res = test_str[:N] + K * (len(test_str) - N)
# printing result
print("The resultant string : " + str(res))
OutputThe original string is : geeksforgeeks
The resultant string : geek@@@@@@@@@
Time Complexity: O(n) -> string slicing
Auxiliary Space: O(n)
Method #2 : Using ljust() + slicing + len()
In this, the task of assigning remaining characters is done using ljust, rather than the * operator.
Python3
# Python3 code to demonstrate working of
# Retain N and Replace remaining by K
# Using ljust() + slicing + len()
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing length needed
N = 4
# initializing remains char
K = "@"
# ljust assigns K to remaining string
res = test_str[:N].ljust(len(test_str), K)
# printing result
print("The resultant string : " + str(res))
OutputThe original string is : geeksforgeeks
The resultant string : geek@@@@@@@@@
Time Complexity: O(n) -> string slicing
Auxiliary Space: O(n)
Method 3 (Using replace() method):
Use the replace method to replace the characters except the first N elements.
Python3
# Python3 code to demonstrate working of
# Retain N and Replace remaining by K
def changedString(test_str):
res = test_str.replace(test_str[N:], K*len(test_str[N:]))
# Printing result
return str(res)
# Driver code
if __name__ == '__main__':
# Initializing string
test_str = 'geeksforgeeks'
# Initializing length needed
N = 4
# Initializing remains char
K = "@"
# Printing original string
print("The original string is : " + str(test_str))
print("The resultant string is : ", end = "")
print(changedString(test_str))
OutputThe original string is : geeksforgeeks
The resultant string is : geek@@@@@@@@@
Time Complexity: O(n) -> average of string slicing and replace function
Auxiliary Space: O(n)
Method 4: Using a loop and concatenation.
Algorithm:
- Initialize an empty string, say res.
- Traverse through the characters of the input string, test_str.
- Check if the index is less than N.
a. If the index is less than N, append the character at that index to res.
b. Else, append the character K to res. - Return the resultant string, res.
Python3
# Python3 code to demonstrate working of
# Retain N and Replace remaining by K
# Using a loop and concatenation
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing length needed
N = 4
# initializing remains char
K = "@"
res = ''
for i in range(len(test_str)):
if i < N:
res += test_str[i]
else:
res += K
# printing result
print("The resultant string : " + str(res))
#this code contributed by tvsk
OutputThe original string is : geeksforgeeks
The resultant string : geek@@@@@@@@@
Time Complexity: O(n), where n is the length of the input string. The loop runs n times.
Auxiliary Space Complexity: O(n), where n is the length of the input string. The size of the resultant string can be the same as the size of the input string, in case N is less than or equal to the length of the input string.
Method 5: Using string format():
Algorithm:
1.Initialize the string to be modified and the length needed and the character to replace remaining characters with.
2.Use string slicing to obtain the first N characters of the original string and concatenate it with K multiplied by the difference between the length of the original string and N.
Python3
# Define the original string
test_str = 'geeksforgeeks'
# Define the number of characters to retain
N = 4
# Define the character to replace the remaining characters with
K = "@"
# Concatenate the first N characters of the original string with K multiplied by the difference between the length of the original string and N
res = '{0}{1}'.format(test_str[:N], K*(len(test_str)-N))
# Print the original string
print("The original string is : " + str(test_str))
# Print the result
print("The resultant string : " + str(res))
#This code is contributed by Jyothi pinjala.
OutputThe original string is : geeksforgeeks
The resultant string : geek@@@@@@@@@
Time Complexity: O(N), where N is the length of the original string. The slicing operation takes O(N) time.
Auxiliary Space: O(N), where N is the length of the original string. The resultant string can take up to N characters.
Method 6: Using map() function and lambda function
Steps were to solve using map and lambda:
- Initialize the original string test_str, number of characters to retain N and the character to replace the remaining characters with K.
- Concatenate the first N characters of the original string with K multiplied by the difference between the length of the original string and N.
- Print the original string and the resultant string.
Python3
# Define the original string
test_str = 'geeksforgeeks'
# Define the number of characters to retain
N = 4
# Define the character to replace the remaining characters with
K = "@"
# Print the original string
print("The original string is : " + str(test_str))
res = ''.join(map(lambda x: x[1] if x[0] < N else K, enumerate(test_str)))
# Print the result
print("The resultant string : " + str(res))
# This code is contributed by Vinay Pinjala.
OutputThe original string is : geeksforgeeks
The resultant string : geek@@@@@@@@@
Time Complexity:
The time complexity of this code is O(N) because the number of iterations in the for loop is proportional to the value of N.
Space Complexity:
The space complexity of this code is O(N) because we are storing the output string in a new variable which has a length equal to the length of the original string.
Method 7: Using string concatenation and conditional operator
The idea is to iterate over the original string and concatenate the first N characters to the result string. For the remaining characters, replace them with the specified character K.
Python3
test_str = 'geeksforgeeks'
N = 4
K = "@"
res = ""
for i in range(len(test_str)):
res += test_str[i] if i < N else K
print("The resultant string : " + str(res))
OutputThe resultant string : geek@@@@@@@@@
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n) as we are using an additional string to store the result.
Similar Reads
Python program to replace first 'K' elements by 'N'
Given a List, replace first K elements by N. Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 4, N = 3 Output : [3, 3, 3, 3, 4, 2, 6, 9] Explanation : First 4 elements are replaced by 3. Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 2, N = 10 Output : [10, 10, 6, 8, 4, 2, 6, 9] Explanation : Fi
5 min read
Python | Retain K Front and Rear elements
Sometimes, we require to shrink a list by deletion of its certain elements. One of the methods that is employed to perform this particular task is front and rear element retention and deletion of rest elements. It is a good utility whose solution can be useful to have. Letâs discuss certain ways in
8 min read
Python Program to replace list elements within a range with a given number
Given a range, the task here is to write a python program that can update the list elements falling under a given index range with a specified number. Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], i, j = 4, 8, K = 9 Output : [4, 6, 8, 1, 9, 9, 9, 9, 12, 3, 9, 1] Explanation : List is u
3 min read
Python | Remove elements of list that are repeated less than k times
Given a list of integers (elements may be repeated), write a Python program to remove the elements that are repeated less than k times. Examples: Input : lst = ['a', 'a', 'a', 'b', 'b', 'c'], k = 2Output : ['a', 'a', 'a', 'b', 'b'] Input : lst = [1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4], k = 3Output : [1, 1
4 min read
Python | Rear elements from Tuple Strings
Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the
5 min read
Replace substring in list of strings - Python
We are given a list of strings, and our task is to replace a specific substring within each string with a new substring. This is useful when modifying text data in bulk. For example, given a = ["hello world", "world of code", "worldwide"], replacing "world" with "universe" should result in ["hello u
3 min read
Python | Remove the given substring from end of string
Sometimes we need to manipulate our string to remove extra information from the string for better understanding and faster processing. Given a task in which the substring needs to be removed from the end of the string using Python. Â Â Remove the substring from the end of the string using Slicing In
3 min read
Python - Restrict Tuples by frequency of first element's value
Given a Tuple list, the task is to write a Python program to restrict the frequency of the 1st element of tuple values to at most K. Examples: Input : test_list = [(2, 3), (3, 3), (1, 4), (2, 4), (2, 5), (3, 4), (1, 4), (3, 4), (4, 7)], K = 2 Output : [(2, 3), (3, 3), (1, 4), (2, 4), (3, 4), (1, 4),
3 min read
Python - Random Replacement of Word in String
Given a string and List, replace each occurrence of K word in string with random element from list. Input : test_str = "Gfg is x. Its also x for geeks", repl_list = ["Good", "Better", "Best"], repl_word = "x" Output : Gfg is Best. Its also Better for geeks Explanation : x is replaced by random repla
3 min read
Python - Replace all numbers by K in given String
We need to write a python program to replace all numeric digits (0-9) in a given string with the character 'K', while keeping all non-numeric characters unchanged. For example we are given a string s="hello123world456" we need to replace all numbers by K in the given string so the string becomes "he
2 min read