Open In App

Python - Retain first N Elements of a String and Replace the Remaining by K

Last Updated : 10 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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))

Output
The 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))

Output
The 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))

Output
The 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:

  1. Initialize an empty string, say res.
  2. Traverse through the characters of the input string, test_str.
  3. 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.
  4. 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

Output
The 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.

Output
The 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.

Output
The 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))

Output
The 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.


Next Article
Practice Tags :

Similar Reads